Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am developing a system using Zend Framework 2 and turn the key config_cache_enabled in application.config.php closures received an error:

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

Searching better I found it was not recommended to use closures in Module.php because that was what caused this error in the configuration cache, thinking about it I read some posts that recommend replacing the closures by factory.

That's what I did, I created a factory and replaces the DI in TableGateway in Module.php by a Factory and worked perfectly, my question is I do not know if it's OK the way I did.

Could anyone tell me if this is the correct 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;
   }
}
like image 832
Cleberson Falk Avatar asked Nov 10 '22 00:11

Cleberson Falk


1 Answers

Yes, this is the way to do factories. You can see examples in SO for example here ZF3 MVC Zend\Authentication as a Service Factory 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 tutorial has been writen for ZF3, this part is fully compatible with the lastest ZF2 version.

like image 164
Al Foиce ѫ Avatar answered Nov 14 '22 23:11

Al Foиce ѫ