Hello everyone!
I must say, I totally fell in love with Phalcon.
I'm trying to create a basic CMS-like application with a mixture of controller based pages and ones created dynamically. In a sense, that users can create pages as they wish based on html from database and not pre-made controllers / views.
My initial idea was simple - set up a basic route for all known pages and use 404 handler to redirect to the 'dynamic' page generator
$router->add(
"/:controller/:action/:params",
array(
"controller" => 1,
"action" => 2,
"params" => 3,
)
);
//Set 404 paths
$router->notFound(array(
"controller" => "pages",
"action" => "dynamic"
));
In theory - this was great. But in practice, it doesn't work. For example, test.com/someth/to/test still matches the first route and since the controller doesn't exist, Phalcon shows "SomethController handler class cannot be loaded" error.
Has anyone got some suggestions on how to overcome that? Is there a way to override the default 'controller not found' phase?
Thanks
EDIT Ach, only just found this: https://forum.phalcon.io/discussion/106/difference-between-setdefaults-and-notfound#C442
If anyone is interested in the solution:
$di->set('dispatcher', function() use ($di) {
//Obtain the standard eventsManager from the DI
$eventsManager = $di->getShared('eventsManager');
//Listen for events produced in the dispatcher using the Security plugin
$eventsManager->attach('dispatch', $security);
$eventsManager->attach("dispatch", function($event, $dispatcher, $exception) {
if ($event->getType() == 'beforeException') {
switch ($exception->getCode()) {
case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(array(
'controller' => 'pages',
'action' => 'dynamic'
));
return false;
}
}
});
$dispatcher = new Phalcon\Mvc\Dispatcher();
//Bind the EventsManager to the Dispatcher
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
Problem solved, unless there is a nicer way of doing it?.