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

Setting up custom routing

Hi there,

I've tried to setup custom routing for the first time. To emulate the default behaviour, I've tried the following code. The only thing that works is the '/' option. If I try and load the other options, the URL in the address bar changes but the page doesn't. What am I missing? This code is in index.php.

Thanks.


    /**
     * Setup router
     */
    $di->set('router', function() {

        $router = new \Phalcon\Mvc\Router(false);

        $router->setDefaultController('index');
        $router->setDefaultAction('index');

        $router->add('/', array(
            "controller" => 'index',
            "action" => 'index'
        ));

        $router->add("/:controller/:action/:params", array(
            "controller" => 1,
            "action" => 2,
            "params" => 3
        ));

        $router->handle();

        return $router;

    });

Do you have controllers set up for your other routes?



38.8k

I have all of the the same controllers avalable that I created when using the default Phalcon route(s). Initially, I just want to see that my custom routing follows Phalcon's default so that I know I have understood it all correctly.

The code I have shown in my initial message seem to cover all bases but it just doesn't work. Phalcon seems to ignore the default action. For example, if I click the "Gallery" link, the URL changes to /gallery but nothing happens. If I add 'index' in the URL so it looks like /gallery/index, then it seems to work.

I also tried specifying defaults in the array style (shown in the docs) but that didn't work either.

Any ideas?

Thanks.



38.8k

Thanks for this! Worked like a charm :)