When a class needs to be provided with hard dependencies best practice is to use a constructor injection pattern where those dependencies are injected using a factory.
Let's assume that MyClass
is hard dependent on a value $dependency
that needs to be resolved from the application config.
<?php
namespace Application\Folder;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyClass
{
protected $dependency;
public function __construct($dependency)
{
$this->dependency = $dependency;
}
}
To inject this dependency a factory class is created. This factory will resolve the dependency from the config and inject the config value on construction of the class and return the result:
<?php
namespace Application\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyClassFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $servicelocator->get('Config');
$dependency = $config['dependency'];
$myClass = new MyClass($dependency);
return $myClass;
}
}
Now that the factory class has been created it has to be registered inside the service manager config in the module config file module.config.php
under the key factories. It is good practice to use the same names for both the class and the factory so it is easy to find them in the project folder tree:
<?php
namespace Application;
return array(
//...
'service_manager' => [
'factories' => [
'Application\Folder\MyClass' => 'Application\Factory\MyClassFactory'
]
],
//...
);
Alternatively the class name constants can be used to register them:
<?php
namespace Application;
use Application\Folder\MyClass;
use Application\Factory\MyClassFactory;
return array(
//...
'service_manager' => [
'factories' => [
MyClass::class => MyClassFactory::class'
]
],
//...
);
Now the class can be collected at the service manager using the key that we used when registering the factory for that class:
$serviceManager->get('Application\Folder\MyClass');
or
$serviceManager->get(MyClass::class);
The service manager will find, collect and run the factory and then it returns your class instance with the dependency injected.