object persistence in php

后端 未结 7 1964
孤城傲影
孤城傲影 2020-12-14 02:48

I am fairly new to web programming, I have mainly used java to create desktop applications in the past.

I\'m trying to figure out how to create persistent objects in

相关标签:
7条回答
  • 2020-12-14 03:13

    Stop using singleton and use dependency injection.

    Best way is to use DataMapper (http://www.martinfowler.com/eaaCatalog/dataMapper.html) and attach it to an object by means of dynamic properties. Let the data mapper handle persistence.

    $CS = new CookieStorage();
    $SS = new SessionStorage();
    $FS = new FileStorage('config/object.db');
    
    $DM = new ObjectDataMapper($FS);
    
    $O  = new Object($DM);
    
    $Object->DynamicProperty = 1;
    

    Now DynamicProperty will automatically persist and will automatically be loaded from file object.db. And the class definition:

    class Object
    {
        public function __construct(MapperInstance $Storage = NULL)
        {
            $this->setMapper($Storage?: new ObjectDataMapper(new FileStorage('config/object.db')));
        }
    
        public function __get($name)
        {
            $this->_Mapper->getProperty($name);
        }
    
        public function __isset($name)
        {
            $this->_Mapper->isProperty($name);
        }
    
        public function __set($name, $value)
        {
            $this->Mapper->setProperty($name, $value);
        }
    }
    
    0 讨论(0)
提交回复
热议问题