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 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题