Yii 2.0 – Where did ActiveRecord Scopes go?

The Yii Framework team recently released their second major version, 2.0.  The version is still a little rough around the edges, but my first impression is that it is a solid replacement for their last major version, 1.1.

ActiveRecord has been given a facelift in 2.0, and one of the 1.1 features – scopes – isn’t mentioned until the very end of the ActiveRecord guide page.  While it was convenient to declare scopes in 1.1 to filter results down to the ones that matter to you at the moment, it also mixed much query logic inside the model.  The developers made the decision to require the use of a separate ActiveQuery class if you want to use a scope-style pattern.

In practice, there isn’t much new work here – just another class that you need to create and an override of your model’s find function.  Check out the pattern below, as detailed in the Yii documentation.

namespace app\models;

use yii\db\ActiveRecord;
use yii\db\ActiveQuery;

class Comment extends ActiveRecord
{
    public static function find()
    {
        return new CommentQuery(get_called_class());
    }
}

class CommentQuery extends ActiveQuery
{
    public function active($state = true)
    {
        return $this->andWhere(['active' => $state]);
    }
}
Share this page:
  • Facebook
  • Twitter
  • Reddit
  • Google Bookmarks
  • email
  • Print
  • RSS
  • Digg
  • StumbleUpon
  • del.icio.us
  • Slashdot
  • Technorati
  • Tumblr

Steven Michaels

Steven Michaels specializes in PHP web applications utilizing MediaWiki, WordPress, Yii Framework and others. He is an open source contributor and leads development for both of Hollow Developers' internal projects, HollowGame and SpeechEase.

Facebook comments:

Leave a Reply