I'd like to be able to use transparent (poor mans) caching of objects by using the constructor and not some factory method.
$a = new aClass(); should check if this objects exists in cache and if it doesn't exist create it and add it to the cache.
Some pseudo-code:
class aClass {
public function __construct($someId) {
if (is_cached($someId) {
$this = get_cached($someId);
} else {
// do stuff here
set_cached($someId, $this);
}
}
}
Unfortunately, this is impossible because you can't redefine $this in php.
Any suggestions?
This will not work because ctors dont return and you cannot redefine $this.
You can use a static factory method instead:
class Foo
{
protected static $instances = array();
public function getCachedOrNew($id)
{
if (!isset(self::$instances[$id])) {
self::$instances[$id] = new self;
}
return self::$instances[$id];
}
}
$foo = Foo::getCachedOrNew(1);
$foo->bar = 1;
$foo = Foo::getCachedOrNew(1);
echo $foo->bar; // 1
Another alternative would be to use a Dependency Injection Container (DIC) that can manage objects instances. Have a look at The Symfony Componenent DIC. for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With