1
votes

I would like to be able to route something like the following in CakePHP 2.0:

domain.com/london
domain.com/milton keynes

to a specific controller and action.

The application has multiple controllers so it should only use this route if the parameter provided doesn't match a controller name. I achieved this with CakePHP 1.3.12 by adding the following code to the bottom of config/routes.php

Router::connect(
  '/:location',
  array('controller' => 'articles', 'action' => 'testing'),
  array('pass' => array('location'), 'location' => '[a-z ]+')
);

Using this code with CakePHP 2.0 only works if I comment out the require line from config/routes.php, but then I loose the default routes so that a URL pointing at any other controller is caught by this.

How can I achieve the desired routing?

2

2 Answers

1
votes

As far as I know this shouldn't work in Cake 1.3 either, simply because your [a-z ]+ regex also matches the case for a simple /controller_name route; the Router has no way to distinguish between the two and will thus always route to the one it encounters first.

You can, however, create a custom route class to achieve this. Mark Story (one of the Cake devs) wrote an excellent post about it quite some time ago, it's for Cake 1.3 but you can easily apply the principle to 2.0 (I know 'cause I'm using it in my 2.0 app). You can the find the post here.

0
votes

This might not answer the specific question asked above, but it's relevant, this page comes up in search results, and my goal is to save whoever finds it (including future me I guess) some time on not having to research what I just researched.

I needed to add routing with a parameter for a different domain. For example, example.com should behave as usual, while example.org/some_page should route directly to a specific controller and action. So I've added the following to my Config/routes.php:

if ( CakeRequest::host()=='example.org' ) {
    Router::connect('/:my_variable', 
        array(
            'controller'=>'my_controller', 
            'action'=>'my_action'
        ),
        array(
            'my_variable'=>'[a-zA-Z-0-9 ]+', 
            'pass'=>array('my_variable')
        )
    );
}