Is there named scope's analog for Doctrine2?
Does Doctrine2 have a features similar to ActiveRecord's named scopes?开发者_如何学Go
There isn't one baked into D2, but it probably wouldn't be too much of a stretch to implement a system similar to Yii's using Doctrine 2's QueryBuilder class, which allows you to construct a query in pieces, using a more programmatic approach.
$qb = $em->createQueryBuilder;
$qb->select('u')
->from('User', 'u')
->where('active IS NOT NULL);
It appears that Yii's implementation stores query criteria in an array, and they are injected into the query when a named scope is used. You could easily do something similar that returns a QueryBuilder object with those params pre-loaded.
class UserRepository extends EntityRepository
{
private $_namedScopes;
public getActiveUsersWhoLoggedInLastWeek()
{
// return a query builder for this model
$qb = $this->_namedScopes->initScope();
// start adding pre-defined criteria
$qb = $this->_namedScopes->addScope($qb, 'active')
$qb = $this->_namedScopes->addScope($qb, 'lastWeek');
return $qb->getQuery()->getResult();
}
}
There are probably several different ways to approach this, so that's just one quick example. The hard part would probably be figuring out how to handle criteria collisions.
http://www.doctrine-project.org/jira/browse/DDC-750
精彩评论