RESTful routes and prefixes with CakePHP

Published on and tagged with cakephp  configuration  tip

Recently, I experimented a bit with RESTful routing in CakePHP. I wanted to have REST urls with a prefix. For example “/example/posts”, with “/example” as prefix. And so I added the following snippet to app/config/routes.php:

Router::mapResources('Posts', array('prefix' => '/example'));

Unfortunately, it doesn’t work, and you get a “Controller not found” error when requesting “/example/posts”, because CakePHP looks for an Example controller instead of a Posts controller. The same error occurs when I remove the leading slash from the prefix, like it is done with “normal” prefix routing:

Router::mapResources('Posts', array('prefix' => 'example'));

At this point I went to the source and found the reason, why it didn’t work: the prefix simply gets concatenated with the underscored controller name while Router::mapResources() generates the necessary routes for the resource. And this means, the prefix must contain a leading and a trailing slash:

Router::mapResources('Posts', array('prefix' => '/example/'));

Not really intuitive ;-)

3 comments baked

© daniel hofstetter. Licensed under a Creative Commons License