user1678586
user1678586

Reputation: 5

Using a factory in a class without injecting the whole service manager in ZF2

I have a class called classB which has multiple dependencies which I am setting up using ClassBFactory. Inside classA I would like to create a new instance of classB using the classBFactory.

Is the only way to get a new instance of classB from its factory by injecting the whole service container into classA, or is there another way? It would seem bad practice to pass in the whole service container as this would give the class access to a lot more than needed.

I've experimented with the following but this won't work as createService() requires the service container, which I would rather not inject into classA

class ClassA {
    protected $classBFactory;
    public function __construct(ClassBFactory $classBFactory)
    {
        $this->classBFactory = $classBFactory;
    }

    public function getNewA()
    {
        return $this->classBFactory->createService();
    }
}

Upvotes: 0

Views: 76

Answers (1)

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

Just create a factory for classA as well where you inject classB into classA. In your factory pull ClassB from the service locator and inject it with contructor injection into ClassA. You should really try to not let your classes depend on the serviceLocator for various reasons, but only let your factories pull from the servicelocator and inject those dependencies with constructor or setter injection (this is called inversion of control).

ClassA

class ClassA {
    protected $classB;
    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }
}

Module.php

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'MyNamespace\ClassA' => function($sm) {
                return new ClassA($sm->get('MyNamespace\ClassB'));
            }, //Using a closure here, but it's better to create a seperate factory class
            'MyNamespace\ClassB' => 'MyNamespace\Factory\ClassBFactory'
        )
    )
}

Upvotes: 0

Related Questions