本文介绍了Yii2 - 在 beforeAction 期间返回响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在构建一个测试 API.我创建了一个从 yii\rest\Controller 扩展的控制器页面.操作需要发送响应.

I am building a test API. I have created a Controller Page which extends from yii\rest\Controller. Actions needs to send a response.

要访问此控制器中的操作,需要发布 service_id 值.如果存在,我需要评估该 service_id 是否存在,它是否处于活动状态并且属于登录的用户.如果验证失败,我需要发送响应.

To access actions in this controller, a service_id value needs to be posted. If present I need to evaluate if that service_id exists, if it is active and belongs to the user logged in. If validation fails, I need to send a response.

我正在尝试使用 beforeAction() 来执行此操作,但问题是返回数据用于验证操作是否应继续.

I am trying to do it using beforeAction(), but the problem is that return data is used to validate if action should continue or not.

所以我的临时解决方案是将服务对象保存在 Class 属性中,以便在操作中对其进行评估并返回响应.

So my temporary solution is saving service object in a Class attribute to evaluate it in the action and return response.

class PageController extends Controller
{

    public $service;

    public function beforeAction($action)
    {
        parent::beforeAction($action);

        if (Yii::$app->request->isPost) {

            $data = Yii::$app->request->post();
            $userAccess = new UserAccess();
            $userAccess->load($data);

            $service = $userAccess->getService();
            $this->service = $service;
        }

        return true;
    }

    public function actionConnect()
    {

        $response = null;

        if (empty($this->service)) {
            $response['code'] = 'ERROR';
            $response['message'] = 'Service does not exist';

            return $response;
        }
    }
}

但我可能有 20 个需要此验证的操作,有没有办法从 beforeAction 方法返回响应以避免重复代码?

But I can potentially have 20 actions which require this validation, is there a way to return the response from the beforeAction method to avoid repeating code?

推荐答案

您可以在 beforeAction() 中设置响应并返回 false 以避免动作调用:

You can setup response in beforeAction() and return false to avoid action call:

public function beforeAction($action) {
    if (Yii::$app->request->isPost) {
        $userAccess = new UserAccess();
        $userAccess->load(Yii::$app->request->post());
        $this->service = $userAccess->getService();

        if (empty($this->service)) {
            $this->asJson([
                'code' => 'ERROR',
                'message' => 'Service does not exist',
            ]);

            return false;
        }
    }

    return parent::beforeAction($action);
}

这篇关于Yii2 - 在 beforeAction 期间返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:52