views:

618

answers:

2

Hi, I'm building an app in PHP and I'm using the data mapper pattern for my DB access. I was considering using the Observer pattern to have all my mappers observe the entities they create, so that they can automatically save any changes back to the database without me having to parse them back manually.

I was just wondering if this was a good idea, or if it's bad practice etc.?

I'm typically working with a few objects that are linked together in a hierarchy, and at the moment having to parse each object to it's mapper manually, which is fairly tedious, so just trying to come up with a better solution.

Thanks, Jack

+3  A: 

Definitely sounds like a good idea to me. What you're doing is similar to the Unit Of Work pattern intended to keep track of the changes you've made to mapped objects and commit (usually as a single transaction) once you're done.

I believe that projects like Outlet and Repose provide this for you in PHP as well as alleviating some of the mapping pain, but I haven't personally used them.

As an aside, it sounds like your object hierarchies may benefit from being viewed as Aggregates if you wish to go down the Domain Driven Design path and benefit from the clean isolation it brings.

--

Edit: it also looks like eZ Components has a fairly full featured PHP ORM solution, and Doctrine 2.0 is shaping up this way too.

--

Edit 2: I wouldn't look at Propel or Creole for the problem you are discussing. Creole is not an ORM, but more of a DB abstraction layer akin to PDO - and the project is now officially "Dead". Propel uses the ActiveRecord pattern, not the DataMapper pattern, so your domain objects end up with a lot more persistence responsibility and AFAIK it does not include a Unit Of Work facility.

Michael Hart
Hi, thanks for the info, I'll certainly look into the projects you mentioned.
Jack Sleight
A: 

If you are looking into ORM's check out Propel and Creole.

Syntax