We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Phalcon Routes and Sub-Domains

I'm very new to PhalconPHP but already like it :-) I have a question if any one could help.

This is the router I'm using in my index.php right now and it works.


$di = new Phalcon\DI\FactoryDefault();

$di['router'] = function() {

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

  switch ($_SERVER['HTTP_HOST']) {
    case 'api.domain.com':

            $router->add('/', 'api::index');
            $router->add('/one', 'api::one');
            $router->add('/two', 'api::two');

        break;

    default:

        $router->add('/', 'index::index');

        break;

  } #switch

        $router->notFound(array(
             'controller' => 'index',
             'action' => 'error'
        ));

        return $router; 

}; #router

But I would like to load this from /app/config/routes.php dynamicly or routes.json file. Something like this or similar.

$routes = array(

    "api.domain.com" => array(
        "/" => array('api' => 'index'),
        "/api1" => array('api' => 'one'),
        "/api2" => array('api' => 'two'),
    ),

    "domain.com" => array(
        "/" => array('index' => 'index'),
    ),

);

Also, is there a shorter way to make "notFound" ?

            $router->notFound(array(
                'controller' => 'index',
                'action' => 'error'
            ));

to something like:

$router->notFound('index::error');

Thanks for any help :-)



3.6k
Accepted
answer

Not sure the code will work, but you can do something like this:


$di = new Phalcon\DI\FactoryDefault();

$di['router'] = function() {

    $router = new Phalcon\Mvc\Router(false);
    $configRouter = include_once('/app/config/routes.php');

    foreach ($configRouter as $host => $routes) {
        foreach ($routes as $uri => $sources) {
            foreach ($sources as $controller => $action) {
                $router->add($uri, array(
                    'controller' => $controller,
                    'action'     => $action
                ))->setHostname($host);
            }
        }
    }

    return $router;

}; #router


16.6k
edited Jan '15

Yeah not working here with this routes.php config. But thank you for trying :-)

$routes = array(

    "api.domain.com" => array(
        "/" => array('api' => 'index'),
        "/api1" => array('api' => 'one'),
        "/api2" => array('api' => 'two'),
    ),

    "domain.com" => array(
        "/" => array('index' => 'index'),
    ),

);


16.6k
edited Jan '15

Actually it works for some routes if I include this array in the index.php file. But for some reason it wont allow loading CamelCasedController.php only the CasedController.php



16.6k
edited Jan '15

Ah no big deal. Thank you for your help. It works well enought!

This is include I used;

$configRouter[] = include_once(__DIR__.'/../app/config/routes.php');