Named routing – dunno if this term even exists in CakePHP ..
What we are trying to achieve here is to redirect to a user profile based on the username entered.
e.g www.example.com/username should redirect him to the user’s profile.
To do this the first thing that we will have to do is change the route.php file of CakePHP ( you can find it in /project_name/app/config).
// route.php
Router::connect('/:username', array('controller' => 'users', 'action' => 'route_to_profile'));
//In case you want the username to follow some pattern add this
Router::connect('/:username', array('controller' => 'users', 'action' => 'route_to_profile'), array('username' => "[a-z0-9]+"));
In the controller page (users_controller.php) add the following function to redirect to users profile page
//users_controller.php
function route_to_profile(){
$username = $this->params['username'];
// search for the id of the user with the given username
$conditions = array('User.username'=>$username);
$fields = array('User.id');
$recursive = -1;
$user = $this->User->find('first',array('conditions'=>$conditions,'fields'=>$fields,'recursive'=>$recursive));
// if found redirect to appropriate page, else redirect to error page
if($user != null){
$user_id = $user['User']['id'];
$this->redirect(array('controller'=>'users','action'=>'view',$user_id),null,true);
}else{
$this->redirect(array('controller'=>'users','action'=>'error'),null,true);
}
}
One problem with the above code is that when we use html helper to generate link to the index action of a controller
we use,
$html->link(__(' View_Text', true),array('controller'=>'controller_name','action'=>'index'));
The link that will be generated by the above function would be
http://www.example.com/controller_name
instead of
http://www.example.com/controller_name/index
The former link will be misinterpreted by the router, because it will consider controller_name as username and will try redirecting to the view page, which is not what we intend to.
Am still looking for solution to this problem, one temporary way could be to generate the index link using the following code
$html->link(__(' View_Text', true),'/controller_name/index');
which will generate the following html ..
http://www.example.com/controller_name/index