Routing
Routing is how CakePHP decides which controller and action should handle an incoming URL. Thanks to convention over configuration, most routes don't need to be written by hand at all.
Convention-Based Default Routing
By default, CakePHP maps URLs to controllers and actions using a simple pattern:
/controller/action/param1/param2. So a request to:
/articles/view/5
automatically maps to the view() action of ArticlesController,
with 5 passed in as the first argument — with no route explicitly
defined anywhere. This works purely from naming conventions:
| URL segment | Maps to |
|---|---|
articles | ArticlesController |
view | view() method (action) |
5 | First argument passed to view() |
Custom Routes: config/routes.php
Default routing covers plenty of cases, but not every URL should match a controller name
directly. When you need a friendlier or more specific URL, you define a custom route in
config/routes.php. For example, mapping a clean /about-us URL to
a static page action:
$routes->connect('/about-us', ['controller' => 'Pages', 'action' => 'display', 'about']);
Here, visiting /about-us calls PagesController::display('about'),
even though nothing about the URL literally spells out "Pages" or "display".
Route Parameters
Routes can also capture dynamic segments of the URL and pass them along as parameters,
using the modern Router::scope() block syntax:
Router::scope('/', function ($routes) {
$routes->connect('/articles/:slug', ['controller' => 'Articles', 'action' => 'view'])
->setPatterns(['slug' => '[a-z0-9\-]+']);
});
This connects a URL like /articles/my-first-post to
ArticlesController::view(), with my-first-post passed in as the
slug parameter — restricted by setPatterns() to only match
lowercase letters, numbers, and hyphens.
Named and Prefixed Routes
CakePHP also supports prefixed routes, which are handy for grouping a
whole section of an application — like an admin area — under a common URL prefix and
controller namespace, so that /admin/articles can be handled by a separate
Admin\ArticlesController without any of the public-facing routing rules
getting in the way.