Data Mapper Pattern - How to select objects by non-ID fields?
I've been working on a CMS project (using Zend Framework) to brush up my skills and have hit a bit of a wall. I decided early on to adopt the data mapper pattern (http://martinfowler.com/eaaCatalog/dataMapper.html) when handling database interaction due to the nice separation in logic between the business model and underlying storage.
An example of why I want this separation is that domain object properties won't necessarily have the same name as the underlying database column (i.e. there's a naming scheme for primary keys and foreign keys helping with automated inserts and lazy loading).
I adapted tutorials following & based on survivethedeepend.com however every sample/example/tutorial implementation I've seen completely ignores how to handle retrieval when the objects aren't being retrieved by ID. I've been checking tutorials across multiple languages to try and get the clue but they all only seem to handle insert, update by ID, delete by ID & select by ID!
So I've got a few questions, the first of which is how would you go about retrieving on non-primary key fields? Is the usual way to create a specific method per required retriev开发者_开发百科al i.e. '$entity->findByName('Bob');'. That seems terribly rigid and unwieldy in the long run.
And how about retrieving for properties on the object which have a different name in the database? I've been thinking about having a generic select method which takes in 3 arguments (the object property name, the modifier to embed in the where clause e.g. '=' or '>' and the value to match). But I don't think this sits with the idea of the fairly rigid structure of the data mapper pattern.
Can anyone please advise on how would be best to proceed? Has anyone come across this & if so, how did you work it?
I'm aware projects like Doctrine exist to handle this however I'd rather develop an 'in-house' solution at this time.
Having a couple of findByXXX()
methods is no more rigid than having getters and setters on your models for your properties.
As for properties that have different names in the database: name your findBy
methods after the object properties, not after the database columns. After all, if your object property is called name
and you have a getName()
and setName()
method, it is only logical that the selector method is called getByName()
, even though the actual database column is called something else.
精彩评论