How to make PHP routes

"Learn how to create slim & powerful php routes with a simple example."

Creating Basic PHP Routes

Routing is the process of mapping URL paths to PHP functions or objects. URLs are mapped to a specific view or action, making it easier for developers to build applications. In this tutorial, we'll show you how to create basic routes using PHP.

Defining a Route

A route is defined using an array of parameters. The array contains the URL path, the controller, and any parameters that should be passed to the controller. The following example defines a route for the URL /hello that calls a controller named HelloController.

$routes = [
    '/hello' => [
        'controller' => 'HelloController',
        'action' => 'index',
    ]
];

The controller is the name of the class that will be called when the route is matched. The action is the method that should be called on the controller. The action is optional; if it is not provided, the index action will be called by default.

Matching a Route

Once the routes have been defined, the URL must be matched to the appropriate route. This is done using the PHP preg_match() function. The following example matches the URL path to the routes array and calls the appropriate controller and action.

$url = $_SERVER['REQUEST_URI'];

foreach ($routes as $pattern => $route) {
    if (preg_match($pattern, $url, $params) === 1) {
        $controller = $route['controller'];
        $action = $route['action'];
        break;
    }
}

$controller = new $controller();
$controller->$action($params);

The preg_match() function matches the URL path to the route pattern, and returns an array of parameters that can be passed to the controller action. The controller and action are then called, and the parameters are passed to the action.

Passing Parameters

Parameters can be passed to the controller action using the $params array. The parameters are matched to the route pattern using regular expression capture groups. For example, the following route will match a URL path with two parameters: an ID and a name.

$routes = [
    '/user/(d+)/([w-]+)' => [
        'controller' => 'UserController',
        'action' => 'show',
    ]
];

The parameters can then be accessed in the controller action using the $params array. The following example shows how the parameters can be accessed in the controller action.

public function show($params)
{
    $id = $params[1];
    $name = $params[2];

    // ...
}

The parameters can then be used to fetch the appropriate data from the database. By following these steps, you can easily create basic routes for your PHP applications.

Answers (0)