Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routing

A route is a rule that ties a page address to the code that builds the response. Every route of the site is written in one file — app/Config/Routes.php. An address missing from this file returns a 404 error.

A simple route

The file already exists and contains the home page route. Add your own below it:

// app/Config/Routes.php
$routes->get('hello', static function () {
    return 'Hello!';
});

Open http://localhost:8080/hello and the word "Hello!" appears on the page. The first argument is the address without a leading slash, the second is a function that returns the response.

A route to a controller

Usually the response code lives not in the routes file but in a controller — a separate class. Then the second argument is the class and method name:

$routes->get('/', 'Home::index');
$routes->get('posts', 'Posts::index');

The address /posts calls the index() method of the Posts class from the app/Controllers folder. Controllers are the subject of the next lesson.

HTTP methods

Each request method has its own route method:

$routes->get('posts', 'Posts::index');
$routes->post('posts', 'Posts::create');
$routes->delete('posts/(:num)', 'Posts::delete/$1');

get opens pages, post accepts forms, put and delete are used for changing and deleting.

Parameters

A part of the address in parentheses is a parameter. $1 passes it to the method as the first argument:

$routes->get('posts/(:num)', 'Posts::show/$1');

The address /posts/5 calls show(5), while /posts/abc returns 404: the (:num) placeholder lets only digits through.

PlaceholderWhat it matches
(:num)Digits only
(:alpha)Letters only
(:segment)Any text without a slash
(:any)Everything to the end of the address

Route names

A route gets a name so that you can refer to it without repeating the address:

$routes->get('posts/(:num)', 'Posts::show/$1', ['as' => 'posts.show']);

The url_to() function builds the address from the name:

echo url_to('posts.show', 5); // http://localhost:8080/posts/5

If the address in the route changes, links by name keep working.

Groups

Routes that share the beginning of the address are combined into a group:

$routes->group('admin', static function ($routes) {
    $routes->get('posts', 'Admin\Posts::index'); // /admin/posts
    $routes->get('users', 'Admin\Users::index'); // /admin/users
});

The php spark routes command prints the list of all routes.

Common mistake

Routes are checked from top to bottom, and the first match wins. If posts/(:segment) sits above posts/new, the address /posts/new falls into the first route. Put exact addresses before addresses with parameters and use (:num) where a number is expected.

Thanks for reading!

Donate to the site — we work hard for you.