我正在尝试编写一个简单的 CakePHP 组件,该组件将检查 php session 变量并在未设置时重定向到特定位置。该函数将在多个 Controller 中使用,我只想将其代码放在一处(DRY 和所有)。
我遇到的问题是 cake 无法使 Controller
函数可供组件访问,因此我无法调用 $this->redirect([routing array])
。
有办法解决这个问题吗?我不想向函数添加 return 语句,然后我必须在 Controller 中检查该语句,因为这就是函数已经执行的所有操作(1 行 if 语句),并且似乎是不必要的抽象层。我打算将该函数放在 cake 外部的一个单独文件中,然后将 include
添加到我所有需要此函数的 Controller 中,作为解决此问题的一种巧妙方法。
最佳答案
在那里你可以看到两个回调
Component::initialize(Controller $controller)
The initialize method is called before the controller’s beforeFilter method.
Component::startup(Controller $controller)
The startup method is called after the controller’s beforeFilter method but before the controller executes the current action handler.
所以,你可以根据你的需要使用initialize(Controller $controller)或startup(Controller $controller)(似乎你需要使用initialize)
按照以下方式
function initialize(Controller $controller ) {
$this->controller = $controller;
}
以及代码中稍后的用户。 CakePHP 将当前 Controller 作为 $controller 的值发送
关于CakePHP:从组件调用 Controller ::重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17324118/