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

Is there a way to use "named" routes?

right now I do this:

$this->response->redirect('mymodule/index');

but I want to use a "virtual" name:

$this->response->redirect('jumpHereIfError');

and define it:

$router->add('jumpHereIfError', array( 'module' => 'frontend', 'controller' => 'mymodule', 'action' => 'index' ));

because if I rename a module, I have to rename 100 redirect() method.



47.7k
Accepted
answer
edited Oct '15

I think this might work:

    $router->add(
        "mymodule/index", // This matches your request url
        array(
            'module' => 'frontend', 
            'controller' => 'mymodule', 
            'action' => 'index'
        ))->setName("jumpHereIfError");

        $redirect_url = $url->get( array('for' => 'jumpHereIfError') );
        $this->response->redirect(  $redirect_url  );

This is a direct excerpt from the docs here:

As of writing for version phalcon 2.0.8:

Each route that is added to the router is stored internally as a Phalcon\Mvc\Router\Route object. That class encapsulates all the details of each route. For instance, we can give a name to a path to identify it uniquely in our application. This is especially useful if you want to create URLs from it.

    <?php

    $route = $router->add("/posts/{year}/{title}", "Posts::show");

    $route->setName("show-posts");

    // Or just

    $router->add("/posts/{year}/{title}", "Posts::show")->setName("show-posts");

Then, using for example the component Phalcon\Mvc\Url we can build routes from its name:

    <?php

    // Returns /posts/2012/phalcon-1-0-released
    echo $url->get(
        array(
            "for"   => "show-posts",
            "year"  => "2012",
            "title" => "phalcon-1-0-released"
        )
    );