Search code examples
phalcon

phalcon forward() doesnt work from helper function


I want to use forward() function inside my helper function. unfortunately I cant manage it.

IndexController:

class IndexController extends ControllerBase

   public function indexAction()
      $helper = new CustomFunctions();
      $helper->log();
      die('still here');

   {
{

CustomFunctions

class CustomFunctions extends \Phalcon\DI\Injectable{
   public function log(){
      //...
      $this->dispatcher->forward([
            'controller' => 'error',
            'action'     => 'route404'
        ]);

        return false;
   }

}

why forward didnt work? It should forward me into error controller instead of showing message from index controller. Thank you for all advice.


Solution

  • dispatcher->forward doesn't work that way in Phalcon. It's just a shorthand for firing up another controller and action, but it doesn't exit or return from the current controller or action. In other words, you should probably check if $helper->log(); returns false, if it does, then assume return; or exit; Even if you use redirect instead of forward, which means it sends a header to the client's browser, it still goes through Phalcon and only sent after Phalcon is told to send the headers. This allows you to write tests around things in Phalcon, unlike actually setting stuff with header right away. Not exiting right away allows you to test things like ->forward and ->redirect without stopping your tests in the middle. You might also try the throw approach if you need to emulate early exiting, then catch such an error to decide if it's time to exit;. This approach would give you the benefit of exit; while still being testable. Or you can just toss a die where you already have it, etc, or exit; from your error controller, etc.

    You might want to read up on the Dispatch Loop:
    https://docs.phalconphp.com/en/3.2/dispatcher