zend 2:在TableGateway中使用Paginator

时间:2014-03-19 15:42:38

标签: sql design-patterns dependency-injection zend-framework2

我在Module.php中配置了我的模型,如下所示:

'MyModule\Model\MyTable' => function($sm) {
    $tableGateway = $sm->get('MyTableGateway');
    $table = new MyTable($tableGateway);
    return $table;
},
'MyTableGateway' => function($sm) {
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(
        new Ticket());
    return new TableGateway('someTable', $dbAdapter, null,
        $resultSetPrototype);
    },

现在我在MyTable.php中执行此操作:

$resultSet = $this->tableGateway->select(
    function(Select $select) {
        $select
            ->order('id ASC')
            ->where->equalTo('aaaa', 2343)
            ->and
            ->where->notEqualTo('bbbb', 'sdfsdf')
            ;
});

现在我想使用分页,但是看看zend tutorial他们你做了这个:

// create a new Select object for the table album
$select = new Select('someTable');
// create a new result set based on the Album entity
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
// create a new pagination adapter object
$paginatorAdapter = new DbSelect(
    // our configured select object
    $select,
    // the adapter to run it against
    $this->tableGateway->getAdapter(),
    // the result set to hydrate
    $resultSetPrototype
);
$paginator = new Paginator($paginatorAdapter);
return $paginator;

为什么我必须$select = new Select('someTable');这是否违反了DI原则,因为我静态输入了表格的名称?在Module.php中配置表名并且仍然需要在实际模型中对其进行硬编码似乎是正确的。我能以某种方式从服务管理器中检索表名吗?

1 个答案:

答案 0 :(得分:1)

根据Crisp的评论

,以下是我的代码现在的样子
$select = new Select($this->tableGateway->getTable());

$paginatorAdapter = new DbSelect(
    $select,
    $this->tableGateway->getAdapter(),
    $this->tableGateway->getResultSetPrototype()
);
$paginator = new Paginator($paginatorAdapter);

return $paginator;

很奇怪他们在教程中并没有像这样做。