Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



24.3k
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"
        )
    );