3

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?

2
  • and what a problem with factory ? Commented Mar 7, 2012 at 9:28
  • 1
    First, I want transparency and second I don't want to rewrite hundreds of thousands lines of code. Commented Mar 7, 2012 at 10:16

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

As I mentioned, I don't want to use a factory method to create the object, I want transparent caching. But I looks like this is not possible with php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.