使用Zend_DB ResultSet(ZF2)自动匹配数据库列

时间:2016-08-25 08:06:55

标签: php zend-framework2 zend-db

在我的“Module.php”中,我在getServiceConfig()

中有这段代码
                'FoobarTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('dbfoobar');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Foobar());
                return new TableGateway('foobartable', $dbAdapter, null, $resultSetPrototype);
            },

现在,我必须使用“exchangeArray($data)”方法编写匹配的类,其中我必须将每个列与类属性匹配。 这可行,但是:

如何在不必手动编写匹配的情况下编写此代码? 有没有“自动匹配”列的方法,所以我可以在我的实体中处理1:1列?我想,我必须使用setArrayObjectPrototype以外的东西,但我还没有在谷歌上找到任何东西。 任何帮助(某些链接等)都可以,谢谢;)

1 个答案:

答案 0 :(得分:0)

Zf2提供默认的水合作用策略。

$resultSetPrototype = new Zend\Db\ResultSet\HydratingResultSet();
$resultSetPrototype->setHydrator(new Zend\Stdlib\Hydrator\ObjectProperty());
$resultSetPrototype->setObjectPrototype(new Foobar());

objectProperty类型根据对象属性自动水合。 您还有其他类型的ClassMethods,它将使用您的getter / setter方法。

$resultSetPrototype = new Zend\Db\ResultSet\HydratingResultSet();
$resultSetPrototype->setHydrator(new Zend\Stdlib\Hydrator\ClassMethods());
$resultSetPrototype->setObjectPrototype(new Foobar());

您还可以在resultsetprototype中定义自定义水分器,以自动将数据分配给模型。 但是这个解决方案需要你编写你不想要的确切代码行。