Set service to be not shared

I want to set up a service, so that I get a new instance of a particular class, every time I instantiate from the DI. So, the objects should not share data.

I would do that in my services.php like this, without true as a 3rd parameter in the set() method:

$di->set('testclass', function () {
    return new \EE\Library\Inputs\TestClass();
});

But, I found that a second instance of the class does share data with the first instance, which it shouldn't. When I do this:

$test1 = $this->di['testclass'];
$test1->setValue('test 1');

$test2 = $this->di['testclass'];
echo $test2->getValue();

The value test 1 is displayed, while nothing should be. The class is this:

namespace EE\Library\Inputs;

class TestClass
{
    protected $value = '';

    public function setValue($new) {
        $this->value = $new;
    }

    public function getValue() {
        return $this->value;
    }
}

Am I doing something wrong? I checked that it didn't make a difference when I added the parameter true in the set() method. (Phalcon version is 2.0.9)

edited Feb '16

Getting services using array syntax will always return them as shared. Use get method.

I will put some fix in PR for 2.1.x branch, wait for merging it and compile it yourself or wait for 2.1.x

PR with fix for it is waiting in repo : https://github.com/phalcon/cphalcon/pull/11460 for instance if you want now this fix you can clone my repo and build phalcon from it.



1.1k

Thanks, Jurigag. I checked that it indeed works correctly when using $this->di->get("testclass").

I'm glad to hear that this behavior will be changed in 2.1. For now, I'll correct it in my code with a global regex find/replace.