使用 Flash 消息重定向到另一个控制器 - Cakephp 3

Redirect to another controller with a Flash message - Cakephp 3

有一种方法可以使用 Flash 消息从一个组件重定向到另一个控制器(不是调用该组件的控制器)吗?类似于:

namespace App\Controller\Component;

use Cake\Controller\Component;

class ValidateValueComponent extends Component
{
    public function validateValue($var = null){
        try{
            if(!$var){
                throw new \Exception();
            }
        } catch(\Exception $e){
            $action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
            $controller = $action === 'home' ? 'Home' : $this->request->params['controller'];

            $this->_registry->getController()->Flash->error(__('Message!'));
            // $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
        }
    }
}

我想验证一些值并避免它中断执行。如果 $var 上没有值(不为空),我想检查错误是否由 index 方法调用,如果是,则将用户发送到主页 (HomeController),并显示 flash 消息。在另一种情况下,只需将用户从捕获错误的控制器发送到索引并显示 flash 消息。

上面的代码允许我显示 Flash 或重定向,但我不能同时执行它们。

无论如何,

谢谢大家!

实际上,我使用 bookstack.cn 中的 link 解决了问题,但总的来说,我需要在我的 $components 数组上调用 Flash 组件,然后正常使用它,独立于调用该组件的控制器.类似于:

namespace App\Controller\Component;

use Cake\Controller\Component;

class ValidateValueComponent extends Component
{
    public $components = ['Flash'];

    public function validateValue($var = null){
        try{
            if(!$var){
                throw new \Exception();
            }
        } catch(\Exception $e){
            $action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
            $controller = $action === 'home' ? 'Home' : $this->request->params['controller'];

            $this->Flash->set(__('Message!'));
            return $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
        }
    }
}