Yii 1.1: pcpublishedbehavior

Named scope via behavior to filter only 'published' or 'unpublished' records
2 followers

PcPublishedBehavior

Features

  • Easily filter out 'published' or 'unpublished' records when using AR's find*() methods.
  • Supported definition of 'published' in each AR class implementation. One class could define it as published = 0, and another class could define it with different code.

Usage

  • Extract the class file from the package of this extension in your protected/components directory.
  • In each AR class that needs to use this behavior, you need to define the following:
    • An attribute named "status". It should be an int and in MySQL terms it can be defined as tinyint (256 possible statuses is well above my needs...).
    • A constant - STATUS_PUBLISHED . You can also define other statuses but this one is used to determine if a certain model is (==) published or unpublished (!=).
  • In the relevant AR class, you need to define a new behavior like this:
public function behaviors() {
    $parents_behaviors = parent::behaviors();
    $new_behaviors = array(
        'publicityScopes' => array(
            'class' => 'PcPublishedBehavior',
        ),
    );
    return array_merge($parents_behaviors, $new_behaviors);
}
  • After you've defined this behavior, you'll 'get' the methods defined in PcPublishedBehavior in your AR class. Those methods provide the needed named scopes. In order to use the scopes, you need to use the following intuitive syntax:
$posts=Post::model()->published()->findAll();

TODOs

Determining the status of a model based on model constants is nice but it surely can be more robust:

  • Add support for "statusProviderMethodName" property in the behavior class. This property could be used to be dynamically run when publicity status check is needed. This way we can introduce more complex logic that decides if a record is published or not.

Resources

Be the first person to leave a comment

Please to leave your comment.

Create extension