yii2yii-rest

yii2 global behavior to check language in module


I have api module in Yii2 app. Before any reuqest I need to check did user send language in post or get request. If user did not send language then throw exception with 422 code.

I have module Api.php. I should configure only for this module.


Solution

  • Create behavior BeforeActionValidator, then create method beforeAction inside create validation rule with HttpException. Here is example:

    class BeforeActionValidator extends Behavior
    {
    
        public $rules = [];
    
        public function events()
        {
            return [
                Controller::EVENT_BEFORE_ACTION => 'beforeAction'
            ];
        }
    
    
        public function beforeAction()
        {
            $lang = Yii::$app->request->get('lang', null)??Yii::$app->request->post('lang', null);
            if ($lang == null) {
                throw new HttpException(422,"lang is required");
            }
        }
    }
    

    And then attach this behavior to config file. In your module.

    public function init()
        {
            parent::init();
    
            \Yii::configure($this,
                [
                    'as globalAccess' => [
                        'class' => BeforeActionValidator::class,
                    ]
                ]);
        }
    

    If you want you can add other events. Like AFTER_REQUEST