Redirect from a component in cake 3.4


#1

Hi all,

I made a component with a public method that in certain condition needs to redirect the user to a page.

Before cake 3.4 i did something like this:

class MyComponent extends Component
{
    ...
    public function check()
    {
        ...
        $this->controller->redirect(['_name' => 'example']);
        $this->controller->response->sendHeaders();
        $this->controller->response->stop();
    }
    ...
}

And then I called that method inside some controllers, like this:

class MyController extends AppController
{
    ...
    public function index()
    {
        $this->MyComponent->check();
        ...
    }
    ...
}

Now that both Response::sendHeaders() and Response::stop() are deprecated and that Response has been rewritten to be immutable, how can i redirect the user to a new location using that method?


#2

For now I solved by changing the method to this:

class MyComponent extends Component
{
    ...
    public function check()
    {
        ...
        $this->controller->redirect(['_name' => 'example']);
        
        $emitter = new Cake\Http\ResponseEmitter();
        $emitter->emit($this->controller->response);
        exit;
    }
    ...
}

Is this a good solution?