我已经设置了路线:
$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 ($di->has('modulename'))
更新1
据我所知https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/application.zep#L232
如果在 DI 中找不到模块,您可以使用事件管理器并从 beforeStartModule
返回 false
if typeof eventsManager == "object" {
if eventsManager->fire("application:beforeStartModule", this, moduleName) === false {
return false;
}
}
更新2
您还可以使用调度程序设置:
// 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;
});
关于php - Phalcon - 如果不存在则模块异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31671787/