Working with Routes in Your Own MVC Framework
You already know that in the file /project/config/routes.php
routes are placed, indicating the correspondences
between URLs and controllers with actions. Routes
are objects of the Route class.
Let's create this class in the file
/core/Route.php:
<?php
namespace Core;
class Route
{
private $path;
private $controller;
private $action;
public function __construct($path, $controller, $action)
{
$this->path = $path;
$this->controller = $controller;
$this->action = $action;
}
public function __get($property)
{
return $this->$property;
}
}
?>
As you can see, the properties in this class are intended for reading only, which is achieved by using magic methods.
Now take a look at the file with routes. You can
see that there is an array there that
is returned via return. This means
that if you include such a file via require,
the result of the inclusion can be written to a
variable, and that variable will contain our
array:
<?php
namespace Core;
error_reporting(E_ALL);
ini_set('display_errors', 'on');
spl_autoload_register(function($class) {
// your autoload implementation
});
// Read the array from the file with routes into a variable:
$routes = require $_SERVER['DOCUMENT_ROOT'] . '/project/config/routes.php';
?>
Copy the code of my Route class
and place it in the file
/core/Route.php.
Get the array with routes in the index.php file.