Zend Framework 2 - replace closures with factory in Module.php

I am developing a system using Zend Framework 2 and turning the config_cache_enabled key in application.config.php . Closing got an error:

Fatal error: calling the undefined set_state Closure :: __ () method in /home/user/www/myProject.com/data/cache/module-config-cache.app_config.php online 185.

Searching better, I found that it is not recommended to use closure in Module.php because it caused this error in the configuration cache, thinking about it, I read a few posts that recommend replacing closures with factory.

What I did, I created a factory and replaced the DI in TableGateway in Module.php with factory and worked fine, my question is: I don't know if this is good, how I did it.

Can someone tell me if this is the right way to solve the problem?

application.config.php - before:

 'Admin\Model\PedidosTable' => function($sm) { $tableGateway = $sm->get('PedidosTableGateway'); $table = new PedidosTable($tableGateway); return $table; }, 'PedidosTableGateway' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new Pedidos()); return new TableGateway('pedidos', $dbAdapter, null, $resultSetPrototype); }, 

application.config.php - after:

 'factories' => array( 'PedidosTable' => 'Admin\Service\PedidosTableFactory', ), 'aliases' => array( 'Admin\Model\PedidosTable' => 'PedidosTable', ), 

TableFactory:

 namespace Admin\Service; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Db\ResultSet\ResultSet; use Zend\Db\TableGateway\TableGateway; use Admin\Model\Pedidos; use Admin\Model\PedidosTable; class PedidosTableFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new Pedidos()); $tableGateway = new TableGateway('pedidos', $dbAdapter, null, $resultSetPrototype); $table = new PedidosTable($tableGateway); return $table; } } 
+5
source share
1 answer

Yes, this is a way to make factories. You can see examples in SO, for example, here ZF3 MVC Zend \ Authentication as a Factory service and, of course, in the Zend "In-Depth" tutorial: https://docs.zendframework.com/tutorials/in-depth-guide/ models-and-servicemanager / # writing-a-factory-class . Even if this manual was written for ZF3, this part is fully compatible with the latest version of ZF2.

0
source

Source: https://habr.com/ru/post/1237535/


All Articles