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

I understand the importance of Injection Dependency and its role in unit testing, so the following problem gives me a pause:

In one area where I cannot use Singleton, the Identity Map / Unit of Work template is used (which contains tabs in the state of the domain object).

//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 tips on how you could handle this situation?

I would be sorry to transfer / generate instances of access to the map / database to the domain object itself to satisfy the DI - At the same time, avoiding this, you get a lot of calls inside the domain object for external static methods.

, , "" , . , , . Active Record - - .

+3
1

, , , , , FI: user_User - , user_mapper_User - mapper.

domainObject , mapper.

, __call() domainObject.

+1

Source: https://habr.com/ru/post/1742425/


All Articles