2017 © Pedro Peláez
 

library yii2-before-query

Add before query or before find event on Yii 2 models

image

mootensai/yii2-before-query

Add before query or before find event on Yii 2 models

  • Monday, June 29, 2015
  • by mootensai
  • Repository
  • 1 Watchers
  • 2 Stars
  • 52 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 1 Forks
  • 1 Open issues
  • 1 Versions
  • 41 % Grown

The README.md

yii2-before-query

Add before query event on Yii 2 models, (*1)

Installation

The preferred way to install this extension is through composer., (*2)

Either run, (*3)

$ composer require mootensai/yii2-before-query "dev-master"

or add, (*4)

"mootensai/yii2-before-query": "dev-master"

to the require section of your composer.json file., (*5)

1. Base Trait Before Query

namespace common\traits\base;
trait BeforeQueryTrait{

    public static function find() {
        $obj = new static;
        $class = new \ReflectionClass($obj);
        $condition = [];
        foreach ($class->getProperties(\ReflectionProperty::IS_STATIC) as $property) {
            if(strpos($property->getName(),'BEFORE_QUERY') !== false && is_array($property->getValue($obj))){
                $condition = array_merge($condition, $property->getValue($obj));
            }
        }
        return parent::find()->andFilterWhere($condition);
    }
}

2. Add new property on model

Next, you can add new property on your model like this :, (*6)

class MyClass extends \yii\db\ActiveRecord{
    use \common\traits\base\BeforeQueryTrait;
    public static $BEFORE_QUERY = ['myColumn' => 'myValue'];
}

NB : the content of your public static $BEFORE_QUERY can be learn here, (*7)

http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where%28%29-detail, (*8)

3. You can create a new trait.

For example, i've created Soft Delete Boolean Trait :, (*9)

trait SoftDeleteBoolTrait{
    public static $BEFORE_QUERY_SOFT_DELETE = ['isdeleted' => 0];

    public function deleteSoft() {
        $col = key(static::$BEFORE_QUERY_SOFT_DELETE);
        $this->{$col} = 1;
        return $this->save(false,[$col]);
    }

    public static function restore($id) {
        $col = key(static::$BEFORE_QUERY_SOFT_DELETE);
        $model = parent::findOne($id, 1);
        $model->{$col} = 0;
        $model->save(false,[$col]);
    }
}

Use it on model :, (*10)

class MyClass extends \yii\db\ActiveRecord{
    use \mootensai\beforequery\base\BeforeQueryTrait;
    use \mootensai\beforequery\traits\SoftDeleteBoolTrait;
}

The Versions

29/06 2015

dev-master

9999999-dev http://github.com/mootensai/yii2-before-query

Add before query or before find event on Yii 2 models

  Sources   Download

None

The Requires

  • php >=5.4.0

 

by Yohanes Candrajaya

yii2 query before find before query beforefind before find