Yii2 在控制器内映射 Action 到其它动作

本文讲解:如何把控制器内的任意一个 Action 映射到另一个 Action。

0x00 准备

  • Yii ^ 2.0.7

0x01 代码

首先定义一个 RedirectAction 类。

class RedirectAction
{
    protected $actionId;

    public function __construct($actionId)
    {
        $this->actionId = $actionId;
    }

    public function __invoke($id, \yii\base\Controller $controller)
    {
        return $controller->createAction($this->actionId);
    }
}

接着在控制器内重写实现 actions() 方法,用于映射 Action ID => 实际的动作

class Controller
{
    public function actions()
    {
        return [
            'foo' => new RedirectAction('bar'), // 访问 `module/controller/foo` 将会被重定向至 `actionBar` 方法
            // ...
        ];
    }

    public function actionBar()
    {
        return 'bar';
    }
}

完成。

0xFF 感想

回头再看 Laravel,真心感激 Laravel 的自定义路由...

本作品采用《CC 协议》,转载必须注明作者和本文链接
Former WinForm and PHP engineer. Now prefer Golang and Rust, and mainly working on DevSecOps and Kubernetes.
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
67
粉丝
590
喜欢
1235
收藏
1133
排名:13
访问:32.4 万
私信
所有博文
社区赞助商