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:
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.