We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Dispatcher forward

In index.php i have this code:

<?php

error_reporting(E_ALL/* & ~E_NOTICE*/);

try {
    // LOADING ALL RESOURCES

    $application = new \Phalcon\Mvc\Application($di);
    echo $application->handle()->getContent();

} catch (Ely\Exception\NotFoundException $e) {
    $di->get("dispatcher")->forward(array(
        "controller" => "Index",
        "action" => "route404"
    ));
} catch (\Exception $e) {
    echo $e->getMessage().PHP_EOL;
    print $e->getTraceAsString();
}

And when in my controller i throw this exception:

$mod = Mods::findFirst(array("static_url = :url:", "bind" => array(
    "url" => $staticUrl
)));

if (!$mod)
    throw new Ely\Exception\NotFoundException();

I see only white page and nothing more, no fatal\notice\warning, just white page. If i call dispatcher forward in position of exception all works fine, but this not so cool, because too long and not universally.

What i do wrong?



98.9k

It's not a good practice use exceptions to control the flow of the application. Exceptions must be used for exceptional cases. You can use a dispatcher forward to execute another action or call the appropiate handler in that case: https://docs.phalcon.io/en/latest/reference/dispatching.html#forwarding-to-other-actions

It's not a good practice use exceptions to control the flow of the application.

I don't think so...

But okay, for find another solution i make this:

// ControllerBase.php

protected function notFound() {
    return $this->dispatcher->forward(array(
        "controller" => "Index",
        "action" => "route404"
    ));
}

// UserController.php

public function indexAction($id) {
        $user = Users::findFirst($id);

        if (!$user)
            return $this->notFound();
}

This work, but always needs to be extended from the ControllerBase, which is not always necessary. For example, in the case of the classes that are REST api.

Is it possible to do this from the exception?