Developing a Router in Your Own MVC Framework
Now you need to develop a router. It is a class that will take an array of routes, take the requested URL, and determine which route corresponds to the given URL. After finding the matching route, our class should get the URL parts that correspond to the route parameters.
Let our router return as its result
an object of the Track class, containing the name
of the controller that should be called for
this request, the name of the action, and the parameters from the URL.
Let our Track class have properties
controller, action and params,
which are read-only:
<?php
namespace Core;
class Track
{
private $controller;
private $action;
private $params;
public function __construct($controller, $action, $params)
{
$this->controller = $controller;
$this->action = $action;
$this->params = $params;
}
public function __get($property)
{
return $this->$property;
}
}
?>
Example
For example, let's say the address bar contains
/test/1/2/. Let's say we have a route
that matches this address:
<?php
new Route('/test/:var1/:var2/', 'test', 'index');
?>
This means that the controller name will be test,
the action name - index, and the parameter array
will be the following:
<?php
['var1' => 1, 'var2' => 2]
?>
The goal of this lesson is to write a Router class
that returns an object of the Track class.
The rest does not concern us yet. Let's proceed
to writing this class.
Practical Tasks
Copy the code of my Track class
and place it in the file
/core/Track.php.