PHP OOP: Avoid Singleton/Static Methods in Domain Model Pattern

Posted by sunwukung on Stack Overflow See other posts from Stack Overflow or by sunwukung
Published on 2010-04-23T09:34:01Z Indexed on 2010/04/23 9:43 UTC
Read the original article Hit count: 255

Filed under:
|
|
|
|

I understand the importance of Dependency Injection and its role in Unit testing, which is why the following issue is giving me pause:

One area where I struggle not to use the Singleton is the Identity Map/Unit of Work pattern (Which keeps tabs on Domain Object state).

//Not actual code, but it should demonstrate the point    

class Monitor{//singleton construction omitted for brevity
    static $members = array();//keeps record of all objects
    static $dirty = array();//keeps record of all modified objects
    static $clean = array();//keeps record of all clean objects
}

class Mapper{//queries database, maps values to object fields
    public function find($id){
        if(isset(Monitor::members[$id]){
        return Monitor::members[$id];
    }
    $values = $this->selectStmt($id);
    //field mapping process omitted for brevity
    $Object = new Object($values);
    Monitor::new[$id]=$Object
    return $Object;
}

$User = $UserMapper->find(1);//domain object is registered in Id Map
$User->changePropertyX();//object is marked "dirty" in UoW

// at this point, I can save by passing the Domain Object back to the Mapper
$UserMapper->save($User);//object is marked clean in UoW

//but a nicer API would be something like this
$User->save();

//but if I want to do this - it has to make a call to the mapper/db somehow    
$User->getBlogPosts();

//or else have to generate specific collection/object graphing methods in the mapper
$UserPosts = $UserMapper->getBlogPosts();
$User->setPosts($UserPosts);

Any advice on how you might handle this situation?

I would be loathe to pass/generate instances of the mapper/database access into the Domain Object itself to satisfy DI - At the same time, avoiding that results in lots of calls within the Domain Object to external static methods.

Although I guess if I want "save" to be part of its behaviour then a facility to do so is required in its construction. Perhaps it's a problem with responsibility, the Domain Object shouldn't be burdened with saving. It's just quite a neat feature from the Active Record pattern - it would be nice to implement it in some way.

© Stack Overflow or respective owner

Related posts about php

Related posts about oop