【问题标题】:yii2 global behavior to check language in moduleyii2 全局行为检查模块中的语言
【发布时间】:2018-10-20 10:52:08
【问题描述】:

我在 Yii2 应用中有 api 模块。在任何请求之前,我需要检查用户是否在帖子中发送语言或获取请求。如果用户没有发送语言,则使用 422 代码抛出异常。

我有模块 Api.php。我应该只为这个模块配置。

【问题讨论】:

  • 您好,您能提供更多信息吗?
  • 我有 api 模块。在每个请求中,用户都应该在 GET 或 POST 请求中给出参数“lang”。如果没有我应该抛出异常
  • 你有什么样的控制器? REST 还是 WEB?
  • 你有 REST 控制器?在 api 模块中
  • 是的,我使用休息控制器

标签: yii2 yii-rest


【解决方案1】:

创建行为BeforeActionValidator,然后在使用HttpException创建验证规则中创建方法beforeAction。这是一个例子:

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");
        }
    }
}

然后将此行为附加到配置文件中。在你的模块中。

public function init()
    {
        parent::init();

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

如果您愿意,可以添加其他事件。喜欢 AFTER_REQUEST

【讨论】:

  • Init() 方法在哪里?
  • 在你想要的模块中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多