Let's say that I have a controller named
pages
and there is a method
slug_on_the_fly
public function slug_on_the_fly($slug)
How would my route for this look like?
E.g. for blog controller it would be easy:
$route['blog/(:any)'] = 'pages/slug_on_the_fly/$1';
and then http://localhost/blog/name-of-the-article
works nice
However, what if I want to do it like without blog
so e.g.
http://localhost/name-of-the-article
or http://localhost/another-article-blablabla
How to do it and don't break another routes e.g. $route['friends'] = 'users';
or $route['about-us'] = 'pages/about_us';
?
Because if I do:
$route['(:any)'] = 'pages/slug_on_the_fly/$1';
It will probably ruin everything else or?
Let's assume you have 3 controllers other than pages controller say controller1, controller2 and controller3 then,
Urls are routed in the following order:
$route
(routes.php) are checked in order.[folder/]controller/methodname/args...
is attempted as a fallback.If have a small number of known explicit routes, you can just add them to
$route
:(Routes keys are really parsed as regular expressions with
:any
and:num
are rewritten to.+
and[0-9]+
.)If you have a large number of such routes (probably not a good idea, BTW!) you can just add a wildcard route to the end of
$route
:The regex here means "any url that has no slashes (except maybe last)". You can refine this to describe your slug format if you have any other restrictions. (A good one is
[a-z0-9-]+
.) If your controller finds the slug in the db, you're done. If it doesn't, it must serve a 404.However, you give up the possibility of some implicit routing as Codeigniter doesn't provide any way for a controller to "give up" a route back to the router. For example, if you have a controller named 'foo' and you want a url like
/foo
to route toFoo::index()
, you must add an explicit route for this case because it would be caught by this route and sent toPages::slug_on_the_fly('foo')
instead. In general, you should not have slugs which are also controller class names! This is why you should have a very small number of these url-slugs, if you have any at all!If you have both a large number of these explicit routes and you are not willing to abide by these implicit routing limitations, you can try adding them to
$route
dynamically:routes_extra.php
file whichroutes.php
includes at the end. Write new routes to it as part of saving a page or when you build/deploy the site.Router.php
and add a new routing layer.pre_system
hook which adds the routes.I'm sure there are other ways.
You could use database driven routes.
Add the table
blog_slugs
to your MySQL database:Replace the code in application/config/routes.php with the one below:
All you would have to do then is to create a record when you create a blog entry and you're done:
Maybe this will help you.
Use the 404 override reserved route controller/method. If a valid controller/route doesn't exist, this method will be called. Works great as a catch-all.