PHP › Routing & Middleware
What is routing in a PHP web application, and how does a router determine which piece of code should handle a specific incoming request?
BeginnerAnswer
Routing is the process of mapping an incoming request's URL and HTTP method to a specific piece of code responsible for handling it, typically a controller method or a closure, and a router examines the request and matches it against a list of previously defined route patterns, some of which may contain dynamic segments representing things like a specific resource identifier, executing the corresponding handler once a match is found.
$routes = [
'GET /products' => 'ProductController@index',
'GET /products/{id}' => 'ProductController@show',
];Real-world example A simple custom router matches an incoming GET request for a specific product URL against its list of defined routes, correctly identifying that it should invoke the show method of ProductController along with the captured product identifier.