Reputation: 563
I have set the Route:
$router->add('/:module/:controller/:action/:params', [
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
]);
When I enter URL to the browser, for example: auth/login/index and module under this URL does not exist, so it throws an exception:
Phalcon\Mvc\Application\Exception: Module 'auth' isn't registered in the application container
How can I catch this exception?
SOLUTION:
$router->add('/:module/:controller/:action/:params', [
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
])->beforeMatch(function($uri) use ($application) {
$modules = $application->getModules();
$moduleName = array_filter(explode('/', $uri))[1];
if(!isset($modules[$moduleName]))
return false;
return true;
});
In beforeMatch method I check If module exist.
Upvotes: 2
Views: 1627
Reputation: 3381
For second param you can use closure and check via
if ($di->has('modulename'))
Update1
As I can see https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/application.zep#L232
you can use event manager and return false
from beforeStartModule
if module not found in DI
if typeof eventsManager == "object" {
if eventsManager->fire("application:beforeStartModule", this, moduleName) === false {
return false;
}
}
Update2
Also you can use dispatcher setting:
// Initialize the Dispatcher
$di->setShared('dispatcher', function() use ($eventsManager) {
$dispatcher = new \Phalcon\Mvc\Dispatcher;
// Attach a listener for type "dispatch:beforeException"
$eventsManager->attach('dispatch:beforeException', function($event, $dispatcher, $exception) {
/**
* @var \Phalcon\Mvc\Dispatcher\Exception $exception
* @var \Phalcon\Mvc\Dispatcher $dispatcher
*/
switch ($exception->getCode()) {
case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
case ANY OTHER CODE HERE:
$dispatcher->forward([
'controller' => 'error',
'action' => 'show404'
]);
return false;
}
});
// Setting up the Dispatcher component
$dispatcher->setDefaultNamespace('your_default_namespace_here');
// Obtain the Events Manager from the DI and bind the eventsManager to the module dispatcher
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
Upvotes: 3