使用服务管理器创建Zend \ Db \ TableGateway的实例

时间:2013-12-10 17:19:42

标签: zend-framework2 zend-db tablegateway

我一直在尝试创建Zend\Db\TableGateway的实例,但却无法做到正确。这就是我module.php中的内容:

use Question\Model\QuestionsTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

//other statements and then getServiceConfig()
public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Question\Model\QuestionsTable' =>  function($sm) {
                $tableGateway = $sm->get('AlbumTableGateway');
                $table = new QuestionsTable($tableGateway);
                return $table;
            },
            'AlbumTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new QuestionsTable());
                return new TableGateway('questions', $dbAdapter, null, $resultSetPrototype);
            },
        ),
    );
}

这是我的QuestionsTable.php文件:

namespace Question\Model;
use Zend\Db\TableGateway\TableGateway;

class QuestionsTable
{
    public $usr_id;
    public $title;
    public $description;
    public $status;

    protected $tableGateway;
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
}

这是我得到的错误: Catchable fatal error: Argument 1 passed to Question\Model\QuestionsTable::__construct() must be an instance of Zend\Db\TableGateway\TableGateway,none given.

提前致谢。

1 个答案:

答案 0 :(得分:1)

您好我认为您应该将表类与原型类分开 作为解决方案,您可以在Question \ Model \ Questions中添加另一个类问题,并将其用作原型

$resultSetPrototype->setArrayObjectPrototype(new Questions()); //instead of QuestionsTable

你可以按照来自专辑tuto

Database and models中描述的相同方式进行操作