25 July 2010

This tutorial shows how to do URL routing in CakePHP, if you need your URL to be without controller and view.

The usual URL is example.com/controller/view/param1/..., this tutorial shows how to make URLs without controller and view in CakePHP. You might need this if you are making dynamic menus and you don't want to do all of the menus as separate controllers, there is no point to do that manually.

Configuration file routes.php:

This goes to routes.php in your configuration folder. Comments explain what for those URLs will be, witch are examples this tutorial is about routing so I'm not going to go through models, controllers and views.
Source code viewer
  1. //View posts from specific category
  2. Router::connect('/:category', array('controller' => 'posts', 'action' => 'index'));
  4. //View post from category
  5. Router::connect('/:category/:title', array('controller' => 'posts', 'action' => 'view'));
Programming Language: PHP

Getting parameters from controller:

You can get parameters from URL like this. This gets the title parameter from URL that is defined in our routing.php file.
Source code viewer
  1. $title = $this->params['title'];
Programming Language: PHP

Using other controllers:

You can make routes elsewhere, but they have to be on top of the routes we created earlier or it will be redirected as admin were parameter1.
Source code viewer
  1. Router::connect('/admin/*', array('controller' => 'admin', 'action' => 'index'));
Programming Language: PHP
That is pretty much it, I hope you found this CakePHP routing tutorial useful.