I’m using the data mapper pattern in a PHP app I’m developing and have a question. At present, you request a Site object with a specific ID and the mapper will lookup the row, create an object and return it. However, if you do this again for the same Site you end up with two different objects with identical data. eg.:
$mapper = new Site_Mapper(); $a = $mapper->get(1); $b = $mapper->get(1); $a == $b // true $a === $b // false
So, my question is, should I:
- Store instantiated Site objects in the mapper so I can then check if they already exist before creating a new one (could be a problem if there’s multiple mappers of the same type)
- Do the same as #1 but ensure there is only ever one instances of each mapper
- Do the same as #1 but use a static property so multiple instances isn’t a problem
- Don’t worry about it because it’s probably not a problem
I’d go with caching somehow – static mapper classes would be my first choice, and is what I’ve seen most of. Otherwise, your option 2 (which is the singleton pattern) is probably the best option.
Remember you need to clear this cache when an update is made to avoid returning stale data.
Having said that, unless you are making something to get a lot of use or that does a lot of queries, it may not matter. (your 4)
Also worth looking at for guidance (I’m sure there are many examples, I just know this one best), Propel (http://propel.phpdb.org/) has the caching feature – might be worth looking at how it does it? Or just use it maybe?