Reputation: 1844
I have a website made in PHP Phalcon, and it has several controllers.
Now I need this website to receive words in the URL (example.com/WORD) and check if they exist in the database, but I must continue to support other controllers like example.com/aboutme.
After few hours of trying different methods and searching online I cannot find a way to accomplish this task. The closer intent was creating a Route to redirect non-existing actions to a new controller, but I cannot make this solution work.
Can you think on a solution that may work and share the code/idea? I am not adding any code because I could not get to do anything useful.
Upvotes: 0
Views: 434
Reputation: 23
I see that the question is very old, but I found it while searching for a solution to the same problem, and what worked for me is adding the '/' for the controllers route:
// Page Not Found - 404
$router->notFound(
[
'controller' => 'index',
'action' => 'pageNotFound',
]
);
// Blog page - www.example.com/blog-slug-here
$router->add(
'/{slug}',
[
'controller' => 'BlogPost',
'action' => 'index',
]
)->setName('Blog-post');
$router->add('/:controller/:action/:params',
[
'controller' => 1,
'action' => 2,
'params' => 3
]
);
$router->add('/:controller/:action',
[
'controller' => 1,
'action' => 2
]
);
$router->add('/:controller/',
[
'controller' => 1
]
);
$router->add(
'/',
[
'controller' => 'index',
'action' => 'index',
]
);
This way I can have a blog post URL like www.example.com/admin and an admin area as www.example.com/admin/
Upvotes: 0
Reputation: 1844
After all, rules did not worked, so I came out with a workaround. I am catching the the exception raised when a controller don't exist and running my code there. So far the only issue is the bitter taste of contributing to spaghetti code :-(
try{
$application = new Application($di);
echo $application->handle()->getContent();
}
catch(\Phalcon\Mvc\Dispatcher\Exception $e)
{
$word = substr($e->getMessage(), 0, strpos($e->getMessage(), "Controller"));
// RUN ESPECIFIC CODE HERE
}
Upvotes: 0
Reputation: 3866
This should not be a problem at all. Here are sample routes:
// Default - This serves as multipurpose route definition
// I can use it to create non pretty urls if I don't want to define them.
// Example: profiles/login, profiles/register - Don't need those pretty :)
$router->add('/:controller/:action/:params', ['controller' => 1, 'action' => 2, 'params' => 3]);
$router->add('/:controller/:action', ['controller' => 1, 'action' => 2]);
$router->add('/:controller', ['controller' => 1]);
// Product page - www.example.com/product-slug-here
$router->add('/{slug}', 'Products::view')->setName('product');
// Blog
$router->add('/blog/{slug}', 'Blog::view')->setName('blog');
$router->add('/blog', 'Blog::index')->setName('blog-short');
// Contacts - Pretty urls in native website language
$router->add('/kontakti', 'Blabla::contacts')->setName('contats');
Upvotes: 1