ujjain ujjain - 10 months ago 94
PHP Question

how to set default prefix for routing in CakePHP 3?

I am using prefixes for languages, I am not sure this is the right way, but I don't want to write custom routes for each of my controllers. I have 20 controllers by now (most simple).

I have the problem that /nl/contact and /en/contact are trying to route to nl_index() and en_index(), which is fine for admin routing, but all controllers were programmed multi-lingually and using i18n, so they should use just index(), edit(), etc and not language_ in front of it.

How can this be done? The reason I added these prefixes is that I can use the same controller and functions for more content. I am currently writing Configure.write language in beforeFilter for the languages based on first 2/3 characters of the url (/en, /nl).


I will present you implementation in Croogo CMS based on CakePHP

here is class CroogoRouter

look at this line:

Router::connect('/:locale/:controller/:action/*', array(), array('locale' => '[a-z]{3}'));

This will create Localized routes pattern, where locale variable can be 3 letter language code (read in ISO 639)

so that means, if any of parsed path will begin with 3 letter code it will be used as locale variable passed to AppController

Then look at this file, where is presented usage of such class:

CroogoRouter::connect('/', array('controller' => 'nodes', 'action' => 'promoted'));

as you can see, you will connect some action path (here /) to controller and action, but CroogoRouter will take care of Localizing this path with :locale variable

Note: Don't forget about mentioning MIT license, which is default for Croogo CMS if you are going to use its code ;-)