Although the accepted answer is correct, I will implement mine a little differently, introducing the container into the controller, and then I will get other dependencies in the constructor, like so ...
<?php namespace moduleName\Controller\Factory; use Interop\Container\ContainerInterface; use Zend\ServiceManager\Factory\FactoryInterface; use moduleName\Controller\ControllerName; class ControllerNameFactory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { return new ControllerName($container); } }
Your controller should look something like this:
namespace ModuleName\Controller; use Doctrine\ORM\EntityManager; use Zend\ServiceManager\ServiceManager; class ControllerName extends \App\Controller\AbstractBaseController { private $orm; public function __construct(ServiceManager $container) { parent::__construct($container); $this->orm = $container->get(EntityManager::class); }
In your module.config file, be sure to register the factory as follows:
'controllers' => [ 'factories' => [ ControllerName::class => Controller\Factory\ControllerNameFactory::class, ],
J.Ewa source share