Dima Dz
Dima Dz

Reputation: 538

ZF2 instantiating classes from factories using MutableCreationOptionsTrait: creates the same instance of class no matter what

In ZF2, I have a factory like this

class SomeServiceFactory implements FactoryInterface, MutableCreationOptionsInterface
{
    use MutableCreationOptionsTrait;

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceManager = $serviceLocator->getServiceLocator();
        $formElementManager = $serviceManager->get('FormElementManager');

        if ($this->creationOptions == 'value1') {
            return new SomeService(
                $formElementManager->get('Path\To\Form1'),
                $serviceManager->get('Path\To\Mapper1'),
                new Object1()
            );
        } elseif ($this->creationOptions == 'value2') {
            return new SomeService(
                $formElementManager->get('Path\To\Form2'),
                $serviceManager->get('Path\to\Mapper2'),
                new Object2()
            );
        }
    }
}

In the controller factory, I get several instances of SomeService based on the option value attached at the object creation, like

$service1 = $viewHelperManager->get('Path\To\SomeService', ['valueType' => 'value1']);
$service2 = $viewHelperManager->get('Path\To\SomeService', ['valueType' => 'value2']);

(these services are view helpers with their dependencies).

The problem is that $service2 is the exact same object as $service1 whereas it should have different dependencies. I tried to study the thing a bit, and it seems that the $creationOptions are not updated when assigning $service2 despite the valueType is completely different.

What is wrong?

Upvotes: 0

Views: 89

Answers (1)

Dima Dz
Dima Dz

Reputation: 538

Accidentally bumped into the answer in the comments (@AlexP if you can hear me, thanks buddy!) to the following question:

https://stackoverflow.com/a/28205176/4685379

By default, ZF2 shares the services. If you want to create a new service each time you call the factory, you need to specify the shared directive in the module.confing.php under the appropriate item like this:

'view_helpers' => [
    'factories' => [
        // some factories including the name of the one that 
        // you don't want to create new instances each time it's called
    ],
    'shared' => [
        'Alias\Of\That\Factory' => false,
    ],
],

http://framework.zend.com/manual/current/en/modules/zend.service-manager.quick-start.html#sample-configuration

Upvotes: 0

Related Questions