Implementation of a Router in a Custom MVC Framework
Let's now write a stub of the Router class
according to our calls:
<?php
namespace Core;
class Router
{
private $routes;
public function getTrack($routes, $uri)
{
// there will be code
}
}
?>
In the getTrack method, we must determine
which of the routes corresponds to the given $uri.
To do this, we need to iterate through our array of routes
with a loop:
<?php
namespace Core;
class Router
{
public function getTrack($routes, $uri)
{
foreach ($routes as $route) {
// check $uri and $route
}
}
}
?>
If some route corresponds to the URI, we
should get the values of the route parameters
from this URI and return an object of the Track class:
<?php
namespace Core;
class Router
{
public function getTrack($routes, $uri)
{
foreach ($routes as $route) {
if (checking the match of the route and URI) {
$params = ; // need to get parameters from uri
return new Track($route->controller, $route->action, $params);
}
}
return new Track('error', 'notFound'); // if no route matches
}
}
?>
Copy my stub of the Router class
and place it in the file /core/Router.php.
Implement the described Router class,
returning an object of the Track class as a result.
If you experience difficulties
(which is quite likely), look at the source
code of the framework you used to study MVC.
There, in the Router class, you will find
the missing part of the implementation and my comments
on it.