September 2017
Intermediate to advanced
244 pages
6h 44m
English
Here is an implementation of the Router class at blog/core/Router.php:
<?phpclass Router { private $routes = []; function setRoutes(Array $routes) { $this->routes = $routes; } function getFilename(string $url) { foreach($this->routes as $route => $file) { if(strpos($url, $route) !== false){ return $file; } } }}
Router has two methods, Router::setRoutes(Array $routes) and Router::getFilename(). setRoutes() is taking an array of routes and storing it. Then, the getFilename() method is responsible for deciding which file to serve against which URL. We are not comparing the whole URL but we are using strpos() that checks if the string in $route exists in $url and, if it exists, it returns the appropriate filename.
Read now
Unlock full access