how to create a factory in zend framework 2?

前端 未结 1 936
感情败类
感情败类 2021-01-05 08:17

in my Module.php i have the fallowing methods that i would like to move them in a factory class so that i wont clutter the Module class

相关标签:
1条回答
  • 2021-01-05 08:34

    I usually put my factories into ../module/yourmodule/src/yourmodule/Factory.

    in your ../module/yourmodule/config/module.config.php you then have to configure your service_manager like so:

    'service_manager' => array(
       'factories' => array(
          'yourfactory' => 'yourmodule\Factory\yourfactory',
       ),
    ),
    

    in yourfactory.php You then have to implent the FactoryInterface and set the service locator. Once you done this you should be able to call the service the usual way for controllers, forms etc.

    namespace Application\Factory;
    
    use Zend\ServiceManager\FactoryInterface;
    use Zend\ServiceManager\ServiceLocatorInterface;
    
    class yourfactory implements FactoryInterface
    {
    
    private $config;
    
    private $serviceLocator;
    
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $servicelocator->get('Your\Service');
    }
    

    After that you can just define functions in your yourfactory.php. In your Controller you call functions like so $serviceManager->get('yourfactory')->yourfunction(yourarguments);

    0 讨论(0)
提交回复
热议问题