0
votes

How do I set default controller and default action in PhalconPHP?

I have used this code without success:

$di->set('router', function () {
    $router = new \Phalcon\Mvc\Router();
    $router->notFound(['controller' => 'Index', 'action'=> 'index']);
    $router->setDefaultController('Bookmarks');
    $router->setDefaultAction('index');
    return $router;
});
1

1 Answers

6
votes

It can fail because you did not set the default namespace for the controller. I also had some trouble with the case of the controller name when i switched from windows to linux. Using lower case name seemed to solve the issue.

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

$router->removeExtraSlashes(true);
$router->setDefaultNamespace('App\Controllers\\');
$router->setDefaultController('index');
$router->setDefaultAction('index');

/**
 * Standard MVC routes
 */
$router->add('/', []);

$router->add(
    '/:controller',
    [
        'controller' => 1
    ]
);

$router->add(
    '/:controller/:action/:params',
    [
        'controller' => 1,
        'action'     => 2,
        'params'     => 3
    ]
);

return $router;

Also, notFound method did not work for me. So i attached a listener to the eventsManager to handle this issue.

$di->set('dispatcher', function () use ($di) {
    // ERROR 404 - Page not found
    $evManager = $di->getShared('eventsManager');
    $evManager->attach(
        "dispatch:beforeException",
        function ($event, $dispatcher, $exception) {
            switch ($exception->getCode()) {
                case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(
                        [
                            'controller' => 'error',
                            'action'     => 'show404'
                        ]
                    );
                    return false;
            }
        }
    );
    $dispatcher = new Dispatcher();
    $dispatcher->setEventsManager($evManager);
    return $dispatcher;
}, true);