如何在 Doctrine 中设置默认水合器?
我找不到在 Doctrine 中设置默认水合器的方法.它应该可用.对吧?
I can't find a way to set the default hydrator in Doctrine. It should be available. Right?
http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html#writing-hydration-method
以上文档页面说明了如何创建自定义水合器.这里的缺点是每次执行查询时都需要指定"水合器.
The above documentation page explains how to create a custom hydrator. The drawback here is that you need to "specify" the hydrator each and every time you execute a query.
推荐答案
我通过阅读 Chris Gutierrez 的评论并更改了一些东西来解决这个问题.
I figured this out by reading Chris Gutierrez's comment and changing some stuff.
首先,为 Doctrine_Query 定义一个扩展类.扩展构造函数来定义你自己的补水模式.
First, define an extension class for Doctrine_Query. Extend the constructor to define your own hydration mode.
class App_Doctrine_Query extends Doctrine_Query
{
public function __construct(Doctrine_Connection $connection = null,
Doctrine_Hydrator_Abstract $hydrator = null)
{
parent::__construct($connection, $hydrator);
if ($hydrator === null) {
$this->setHydrationMode(Doctrine::HYDRATE_ARRAY); // I use this one the most
}
}
}
然后,在您的引导程序中,告诉 Doctrine 您的新课程.
Then, in your bootstrap, tell Doctrine about your new class.
Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_QUERY_CLASS, 'App_Doctrine_Query');
Chris Gutierrez 为连接而不是全局定义了属性,但我有多个连接,我想为所有连接使用此默认值.
Chris Gutierrez defined the attribute for the connection instead of globally but I have more than one connection and I want to use this default for all of them.
现在您不必每次构建查询时都调用 Doctrine_Query::setHydrationMode().
Now you don't have to call Doctrine_Query::setHydrationMode() every time you build a query.
这里有更多信息
http://www.学说项目.org/projects/orm/1.2/docs/manual/configuration/en#configure-query-class
以下更改
我发现上面有问题.具体来说,执行Doctrine_Core::getTable('Model')->find(1)"之类的操作将始终返回水合数组,而不是对象.所以我对此做了一些改动,定义了自定义执行方法以在 Query 调用中使用.
I have found a problem with the above. Specifically, doing something like "Doctrine_Core::getTable('Model')->find(1)" will always return a hydrated array, not an object. So I have altered this a bit, defining custom execute methods for use in a Query call.
另外,我添加了内存释放代码.
Also, I added memory freeing code.
class App_Doctrine_Query extends Doctrine_Query
{
public function rows($params = array(), $hydrationMode = null)
{
if ($hydrationMode === null)
$hydrationMode = Doctrine_Core::HYDRATE_ARRAY;
$results = parent::execute($params, $hydrationMode);
$this->free(true);
return $results;
}
public function row($params = array(), $hydrationMode = null)
{
if ($hydrationMode === null)
$hydrationMode = Doctrine_Core::HYDRATE_ARRAY;
$results = parent::fetchOne($params, $hydrationMode);
$this->free(true);
return $results;
}
}
相关文章