dongya9346 2013-11-13 12:17
浏览 53
已采纳

使用TableGateway和Class Factory创建不同类的ResultSet - ZF2

I have a question table in MySQL, a question TableGateway and a QuestionFactory Model. Based on the QuestionType received by the TableGateway I would like to instantiate a different class e.g. TextQuestion(), BoolQuestion() etc. In a fetchall situation this would return a resultset of these different Classes.

Everything so far is fairly standard:

            'Application\Model\QuestionTable' =>  function($sm) {
                $tableGateway = $sm->get('QuestionTableGateway');
                $table = new \Application\Model\QuestionTable($tableGateway);
                return $table;
            },
            'QuestionTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new \Application\Model\QuestionFactory());
                return new \Zend\Db\TableGateway\TableGateway('questions', $dbAdapter, null, $resultSetPrototype);
            },

QuestionTableGateway extends TableGatewayBase which has:

/**
 * fetch all
 * @return resultset
 */
public function fetchAll()
{
    $resultSet = $this->tableGateway->select();
    return $resultSet;
}

So I need to get the QuestionFactory to return a different class based on the QuestionType in the database.

I was thinking of extending the Zend\Db\ResultSet with a application specific version, with a differently implemented of setArrayObjectPrototype() method.

Any help would be greatly appreciated.

Abor.

  • 写回答

1条回答 默认 最新

  • douqi1928 2013-11-13 23:50
    关注

    I did this small app in zend 2 with solution for your problem. Most interesting will be FabResiltSet class which extends from AbstractResultSet and QuestionFab which has array as a map for your classes you want to make.

    https://github.com/Kil0p/FabResultSet

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。