我设置了路线:
$router->add('/:module/:controller/:action/:params', [
'module' => 1,
'controller' => 2,
'action' => 3,
'params' => 4
]);
当我输入浏览器的URL时,例如:auth / login / index和此URL下的模块不存在,因此会引发异常:
Phalcon\Mvc\Application\Exception: Module 'auth' isn't registered in the application container
如何捕获此异常?
解:
$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;
});
在beforeMatch方法中,我检查If模块是否存在。
答案 0 :(得分:3)
对于第二个参数,您可以使用闭包并通过
进行检查if ($di->has('modulename'))
<强> UPDATE1 强>
我可以看到https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/application.zep#L232
如果在DI中找不到模块
,您可以使用事件管理器并从false
返回beforeStartModule
if typeof eventsManager == "object" {
if eventsManager->fire("application:beforeStartModule", this, moduleName) === false {
return false;
}
}
<强> UPDATE2 强>
您也可以使用调度程序设置:
// 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;
});