Simple Routing in a PHP Engine
In the previous lesson, our site had only one group of URLs. Of course, usually a site has several types of addresses.
Each address group will be processed by its own regular expression, which are called routes. Accordingly, the process of matching routes and code for their processing is called routing.
Let's say, for example, we have two types of addresses. Let's write a separate route for each group:
<?php
if (preg_match('#^/page/([a-z0-9_-]+)$#', $url, $params)) {
// one page by slug
}
if (preg_match('#^/page/all$#', $url, $params)) {
// list of all pages
}
?>
For convenience, let's move the processing code of each route into a separate file:
<?php
if (preg_match('#^/page/([a-z0-9_-]+)$#', $url, $params)) {
$page = include 'view/page/show.php';
}
if (preg_match('#^/page/all$#', $url, $params)) {
$page = include 'view/page/all.php';
}
?>
The included files should return an array with the page title and content as their result.
Let's write the code for the first file, which outputs one page by its slug:
<?php
$slug = $params[1];
$query = "SELECT * FROM pages WHERE slug='$slug'";
$res = mysqli_query($link, $query) or die(mysqli_error($link));
$page = mysqli_fetch_assoc($res);
return $page;
?>
And now let's write the code for the second file, which outputs a list of links to all pages:
<?php
$query = "SELECT slug, title FROM pages";
$res = mysqli_query($link, $query) or die(mysqli_error($link));
for ($data = []; $row = mysqli_fetch_assoc($res); $data[] = $row);
$content = '';
foreach ($data as $page) {
$content .= '
<div>
<a href="/page/' . $page['slug'] . '">' . $page['title'] . '</a>
</div>
';
}
$page = [
'title' => 'all pages',
'content' => $content
];
return $page;
?>
After executing one of the conditions, the variable
$page will always contain an array of the same
structure. Let's use this array to
insert the title and content into the site template:
<?php
$layout = file_get_contents('layout.php');
$layout = str_replace('{{ title }}', $page['title'], $layout);
$layout = str_replace('{{ content }}', $page['content'], $layout);
echo $layout;
?>
Let's put it all together and get the following code:
<?php
$url = $_SERVER['REQUEST_URI'];
if (preg_match('#^/page/([a-z0-9_-]+)$#', $url, $params)) {
$page = include 'view/page/show.php';
}
if (preg_match('#^/page/all$#', $url, $params)) {
$page = include 'view/page/all.php';
}
$layout = file_get_contents('layout.php');
$layout = str_replace('{{ title }}', $page['title'], $layout);
$layout = str_replace('{{ content }}', $page['content'], $layout);
echo $layout;
?>
Suppose you have a site with users. Create a page for showing one user, a page for displaying all users, and a page with a form for adding a new user.