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
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);
}
}