簡體   English   中英

在Module.php中配置表的最佳方法 - Zend 2

[英]Best way to configure a Table in Module.php - Zend 2

我使用zend2教程中的默認示例在module.php中設置我的表,但是在我的項目中我有很多表,所以我的module.php太大了。

這是我的默認配置示例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配置放入Application \\ Model \\ UserTable,如下例所示:

             '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);
            },

這個方法對我有用,我的項目沒有任何變化,不顯示任何錯誤,項目繼續正常工作。

那么,教程中的方法是說在separete數組上設置UserTableGateway?

如果我改變默認配置(上面的例子1)在Application \\ Model \\ Table中設置all(如上面的例子2),是一個配置tablesGateway的好方法嗎? 是一個很好的實踐?

謝謝。

簡而言之,你做的很好,但我認為這不是最好的做法。

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);
    }
}

您可以對所有型號以及您可能擁有的任何其他服務重復此操作。

需要考慮的事情

你提到你有很多桌子,我猜很多模特。 這意味着很多工廠都有很多重復的代碼,yuk。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM