Named Scopes


Is it possible to implement, as in

class Post extends CActiveRecord { … public function scopes() { return array( 'published'=>array( 'condition'=>'status=1', ), 'recently'=>array( 'order'=>'create_time DESC', 'limit'=>5, ), ); } }


@Farkhod, You can use other way with extend Criteria.

  1. extend a criteria ```php class PostCriteria extends Phalcon\Mvc\Model\Criteria { /** * @return PostCriteria */ public function published() { return $this->addWhere('status = :status:')->bind(array(':status:' => 1)); }

    /** * @return PostCriteria */ public function recently() { return $this->order('create_time DESC')->limit(5); } } ```

  2. overwrite query method ```php class Post extends Phalcon\Mvc\Model { /** * @return PostCriteria */ public static function query() { $criteria = new PostCriteria(); $criteria->setDI(Phalcon\DI::getDefault()); $criteria->setModelName(getcalledclass());

    return $criteria;

    } } ```

  3. Use it :) ```php $posts = Post::query()->published()->recently()->execute(); ```


Hi, please note that I'm using yii in a couple of websites. This framework offers some really cool features like these "named scopes" (and also "parametrized named scopes" too !) wich are simply defined in the model class as Farkhod noticed ...

Igor's solution is good, but what if you have many scopes for many models ?

I think this could be a build in phalcon feature.

I vote for it :-)

Criteria are great.

@le51 use traits, inheritance, composition, whatever you are familiar with. Inserting scopes in model is bad because you will end with one big class. If you want it, you're free to go, but don't force other developers to break SOLID.


I do not want to force anyone ! But I do not really understand what you mean with "you will end with one big class".

You are adding logic about quering (fetching records from DB) into model definition. IMHO they should be in some kind Repository (Symfony2 way) or Criteria (I think this should be Documentation).


OK, They are already some logic in model definitions (like skipAttribute or even relations), ... I agree that Criteria are good, but as shwon by Igor above (, he creates a criteria for each model class. That is, IMHO, a bit over complicated (But maybe there is a way to write a more general class but it is out of my knowledge).


You can write BaseModel class and all models can extend it.

On other hand you write annotations plugin for your Models to use some sort annotation like: @Criteria BaseCriteria

There is post about extending Model with custom annotations.

The more I think, this sort of annotations would be nice to go to core framework.