jeudi 17 mars 2016

PHP reflection and injection

I have a class that caches other classes that have been instantiated with reflection. Is it possible to execute a function from within the cache class without injecting everything else that has been cached? Here is an example:

<?php

class cache
{
    private $cache = [];

    public function __construct()
    {
        $test1 = new ReflectionClass('test1');
        $this->cache['test1'] = $test1->newInstanceWithoutConstructor();

        $test2 = new ReflectionClass('test2');
        $this->cache['test2'] = $test2->newInstanceWithoutConstructor();
        $this->cache['test2']->init($this);
    }

    public function say_hello($text)
    {
        echo $text;
    }
}

class test1
{
    public $data = 'foobar';
}

class test2
{
    public function init($con)
    {
        $con->say_hello('hello there');
    }
}

new cache;

In this example the class test2 can execute the function say_hello. I have to inject the cache class to accomplish this. However; the class test1 is also injected because its been cached. Obviously in this example it's trivial, but in a modern application with possibly hundreds of cached objects it would be, I assume, horrible. Is there any solution for this? Thank you :)





Aucun commentaire:

Enregistrer un commentaire