2015-06-11 25 views
0

我使用zend2教程中的默認示例在module.php中設置表格,但在我的項目中,我有很多表格,所以我的module.php是太大了。在Module.php中配置表格的最佳方式 - Zend 2

這是我的默認配置例1:

  'UsersTableGateway' => function ($sm) { 
       $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
       $resultSetPrototype = new ResultSet(); 
       $resultSetPrototype->setArrayObjectPrototype(new Users()); 
       return new TableGateway('users', $dbAdapter, null, $resultSetPrototype); 
      }, 
      'Application\Model\UsersTable'=>function ($sm){ 
       $tableGateway = $sm->get('UsersTableGateway'); 
       return new UsersTable($tableGateway); 
      }, 

我的問題是,如果我把UserTableGateway配置到應用程序\型號\用戶表這樣的實例2:

   'Application\Model\UsersTable'=>function ($sm){ 
       $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
       $resultSetPrototype = new ResultSet(); 
       $resultSetPrototype->setArrayObjectPrototype(new Users()); 
       $tableGateway = new TableGateway('users', $dbAdapter, null, $resultSetPrototype); 

       return new UsersTable($tableGateway); 
      }, 

此方法效果對我來說,在我的項目中沒有任何變化,不顯示任何錯誤,項目保持正常工作。

所以,教程中的方式是說要在單獨數組上設置UserTableGateway?

如果我更改默認配置(上面的示例1),像上面的示例2那樣設置Application \ Model \ Table中的所有配置,是配置tablesGateway的好方法嗎?是一個很好的實踐?

謝謝。

回答

1

總之你做的很好,但我會認爲這不是最佳做法。

module.php中配置服務並不是最好的習慣,它會在你發現的時候非常迅速地變得非常混亂。更好的方向是使用ZF2的更多功能來幫助你的困境。

讓我們離開關閉。如果您的模型需要其他依賴性,最好創建factories並將您的Application\Model\UsersTable指向工廠類而不是閉包。例如,在你的module.config.php

'service_manager' => array(
    'factories' => array(
     'Application\Model\UsersTable' => 'Application\Model\Factory\UsersTableFactory' 
    ) 
) 

Application\Model\Factory\UsersTableFactory看起來大致是這樣的:

namespace Application\Model\Factory; 

class UsersTableFactory 
{ 
    public function __invoke(ServiceLocatorInterface $sl) 
    { 
     $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
     $resultSetPrototype = new ResultSet(); 
     $resultSetPrototype->setArrayObjectPrototype(new Users()); 
     $tableGateway = new TableGateway('users', $dbAdapter, null, $resultSetPrototype); 

     return new UsersTable($tableGateway); 
    } 
} 

這可以重複所有的車型,再加上你可以有任何其他服務。

值得考慮

你提到你有很多的表,我猜很多模型。這意味着許多工廠有很多重複的代碼,呃。

這是我們可以使用abstract factories的地方。假設您的模型構造非常相似,我們可能只有一個工廠可以創建所有模型。

我不會寫這些例子,因爲他們可能會變得複雜,如果你調查自己會更好。簡而言之,abstract factory有兩個工作:檢查它可以創建一個服務,並實際創建它。

+0

謝謝!幫助很多。 – rafaelphp

+0

僅僅爲了解,在將服務配置爲工廠時,我們必須在類中使用__construct()方法,如果您將其設置爲可調用的方法,那麼您將使用__invoke()。 – rafaelphp

+0

@rafaelphp工廠我們有兩個選擇。我們可以實現'FactoryInterface'並使用'createService(ServiceLocatorInterface $ sl)'或我的例子中使用的invoke方法。我隨之而去,因爲它更簡單。 – Ankh

相關問題