views:

43

answers:

1

Bit of an abstract problem here. I'm experimenting with the Domain Model pattern, and barring my other tussles with dependencies - I need some advice on generating Identity for use in an Identity Map.

In most examples for the Data Mapper pattern I've seen (including the one outlined in this book: http://apress.com/book/view/9781590599099) - the user appears to manually set the identity for a given Domain Object using a setter:

$UserMapper = new UserMapper;

//returns a fully formed user object from record sets
$User = $UserMapper->find(1);

//returns an empty object with appropriate properties for completion
$UserBlank = $UserMapper->get();
$UserBlank->setId();
$UserBlank->setOtherProperties();

Now, I don't know if I'm reading the examples wrong - but in the first $User object, the $id property is retrieved from the data store (I'm assuming $id represents a row id). In the latter case, however, how can you set the $id for an object if it has not yet acquired one from the data store? The problem is generating a valid "identity" for the object so that it can be maintained via an Identity Map - so generating an arbitrary integer doesn't solve it.

My current thinking is to nominate different fields for identity (i.e. email) and demanding their presence in generating blank Domain Objects. Alternatively, demanding all objects be fully formed, and using all properties as their identity...hardly efficient.

(Or alternatively, dump the Domain Model concept and return to DBAL/DAO/Transaction Scripts...which is seeming increasingly elegant compared to the ORM implementations I've seen...)

A: 

You would use the setId function if you are controlling the IDs, if you want to override the data store ID, or if you want to update/delete the data without having to retrieve it first (i.e. already have the ID from a POST). Another alternative would be calling setId() to reserve an ID by "querying" (insert a record) the data store for the next available ID.

It's not really relevant what the ID is set to until you actually need to use it to reference something. Calling setId with no parameter would do nothing except flag the object as new data. Once you actually try to "get" the ID is when one would be generated. Sort lazy ID generation.

Brent Baisley
thanks for the answer, that's helped me figure out a method for dealing with this. I may set an arbitrary ID on blank entities that is discarded/replaced with row id on save. The question remaining is how to avoid duplicate blank properties prior to save - but I guess this could be resolved by an identity field if one is available (i.e. running a check on all pending DO email fields).many thanks
sunwukung
You can use a static variable (UserMapper::$ids) to track unique values across objects. Make it an array so you can make a "list" you can add/remove from.
Brent Baisley