mmoscosa
mmoscosa

Reputation: 397

CakePHP: Redirect in routes.php

OK, I dont know if I am taking the wrong approach or not but am stuck here...

We have developed our website and we have many controllers expecting ids and special variables, links already redirecting to the controllers passing what is expected.

The new requirement is to use friendlyUrls and the idea is that instead of having:

http://domain.com/search/advanced/term:head/city:/set:show-all/sort:basic-relevance

it now reads

http://domain.com/search/head

or passing options.

http://domain.com/search/in-edinburgh-scotland/by-rating/head

My idea was to, at the beginning of the Routes.php have a simple if such as:

    $friendlyUrl = $_SERVER['REQUEST_URI'];
    $friendlyUrl = split('/', $friendlyUrl);
    foreach ($friendlyUrl as $key => $params) {
        if(empty($params)){
            unset($friendlyUrl[$key]);
        }
        if($params == 'search'){
           Router::connect('/search/*', array('plugin'=>'Search','controller' => 'Search', 'action' => 'advancedSearch', 'term'=>'head));

        }elseif ($params == 'employers') {
            # code...
        }elseif ($params == 'employer-reviews') {
            # code...
        }elseif ($params == 'jobs') {
            # code...
        }
    }

That didn't work, then I tried adding something similar in my AppController and nothing.

All in all the the thing that has to do is:

Anyone has an idea?! Thank you

Upvotes: 1

Views: 1926

Answers (1)

Will
Will

Reputation: 4715

You definitely want to have a look at the routing page in the book

http://book.cakephp.org/2.0/en/development/routing.html

There are tons of options there to match url patterns to pass parameters to the controllers.

Router::connect(
'/search/:term', 
array('controller' => 'search', 'action' => 'advanced'),
array(
    'pass' => array( 'term')
)
);

You should probably set the defaults for city & set & sort in the actions function parameters definitions:

public function advanced($term, $city='optional', $sort = 'basic'){
     // your codes
}

The great thing about doing it this way, is that your $this->Html->link's will reflect the routes in the paths they generate. (reverse routing)

The routes in cake are quite powerful, you should be able to get some decent friendly urls with them. One extra thing I've used is to use a behaviour - sluggable - to generate a searchable field from the content items title - for pages / content types in the cms.

good luck!

Upvotes: 2

Related Questions