Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php object caching within constructor

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?

like image 498
Bernd Goldschmidt Avatar asked Dec 04 '25 10:12

Bernd Goldschmidt


1 Answers

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.

like image 170
Gordon Avatar answered Dec 06 '25 00:12

Gordon