PHP code example of mobileka / scope-applicator-yii2

1. Go to this page and download the library: Download mobileka/scope-applicator-yii2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mobileka / scope-applicator-yii2 example snippets




namespace app\models\queries;

use Mobileka\ScopeApplicator\Yii2\ActiveQuery;

class PostQuery extends ActiveQuery
{
    public function userId($id = 0)
    {
        if ($id) {
            return $this->andWhere(['user_id' => $id]);
        }

        return $this;
    }
}




namespace app\models;

use app\models\queries\PostQuery;
use Mobileka\ScopeApplicator\Yii2\Model;
use Yii;

class Post extends Model
{
    public static function find()
    {
        return Yii::createObject(PostQuery::className(), [get_called_class()]);
    }
}




namespace app\controllers;

use Yii;
use yii\web\Response;
use yii\rest\Controller;
use app\models\Post;

class PostController extends Controller
{
    public function actionIndex()
    {
        return Post::find()->all();
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats'] = [
            'application/json' => Response::FORMAT_JSON
        ];

        return $behaviors;
    }
}



namespace app\controllers;

use Yii;
use yii\web\Response;
use yii\rest\Controller;
use app\models\Post;

class PostController extends Controller
{
    /**
     * Scope configuration array
     */
    protected $scopes = ['userId'];

    public function actionIndex()
    {
        return Post::applyScopes($this->scopes)->all();
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats'] = [
            'application/json' => Response::FORMAT_JSON
        ];

        return $behaviors;
    }
}




namespace app\controllers;

use Yii;
use yii\web\Response;
use yii\rest\Controller;
use app\models\Post;

class PostController extends Controller
{
    /**
     * Scope configuration array
     */
    protected $scopes = [
        'userId' => [
            // here it is!
            'alias' => 'author_id'
        ]
    ];

    public function actionIndex()
    {
        return Post::applyScopes($this->scopes)->all();
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats'] = [
            'application/json' => Response::FORMAT_JSON
        ];

        return $behaviors;
    }
}