zend-framework2 - Zend Framework 2 中的 AlbumTableGateway 用户指南

标签 zend-framework2 tablegateway

当前(2.1)ZF2用户指南的“Database and models”章节中有一段代码片段,我不明白:

( block “使用ServiceManager配置表网关并注入(inject)AlbumTable”)

...
class Module
{
    // getAutoloaderConfig() and getConfig() methods here

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Album\Model\AlbumTable' =>  function($sm) {
                    $tableGateway = $sm->get('AlbumTableGateway');
                    $table = new AlbumTable($tableGateway);
                    return $table;
                },
                'AlbumTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Album());
                    return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }
}

变量$sm稍后将成为Zend\ServiceManager\ServiceManager的实例,对吧? Zend\ServiceManager\ServiceManager#get(...) 方法需要类名作为第一个参数。但没有类AlbumTableGateway。只有两个模型类:Album\Model\Album 和Album\Model\AlbumTable。

这是指南中的错误还是我对代码的理解错误?

谢谢

最佳答案

最好的理解方式是 ServiceManager 的 get() 方法采用键值,而不是类名。键值需要映射到将导致返回类实例的内容。

如果键位于 invokables 部分中,则 ServiceManager 将尝试实例化键指向的字符串(假设它是类名):

'invokables' => array(
    'some_name' => 'My\Mapper\SomeClassName',
),

如果键位于factories部分中,则ServiceManager将执行键指向的回调并期望返回一个对象实例:

'factories' => array(
    'some_name' => function($sm) { return new \My\Mapper\SomeClassName(); },
),

通常,当您需要执行的操作不仅仅是实例化类时,您可以使用工厂 - 通常您需要使用另一个依赖项来设置该类。如果您只需要实例化一个类,请使用可调用的。

关于zend-framework2 - Zend Framework 2 中的 AlbumTableGateway 用户指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032330/

相关文章:

mysql - 使用 TableGateway 在 ZF2 中进行左连接

git - 更新 ".git directory is missing"时 Composer 出错

php - 配置 ZF2 view_manager 以加载 2 个单独的模板映射

zend-framework2 - 在 ZF2 中将组合和排序与表网关一起使用

php - Zend 2 检查选择查询是否返回 NULL

php - 何时使用 tablegateway 和 Adapter

PHP 7 Zend Framework 2 获取Zend Framework版本

php - 如何从MySql在ZF2中显示utf8字符

php - 表单未将帖子值绑定(bind)到实体

php - 编辑后字段变为 NULL