Developing a Dispatcher in Your Own MVC Framework
Let's recall the current contents of the file index.php:
<?php
namespace Core;
error_reporting(E_ALL);
ini_set('display_errors', 'on');
spl_autoload_register(function($class) {
// your autoload implementation
});
$routes = require $_SERVER['DOCUMENT_ROOT'] . '/project/config/routes.php';
$track = ( new Router ) -> getTrack($routes, $_SERVER['REQUEST_URI']);
?>
As you can see, for now our router returns
an object of the Track class, containing the
controller name, action name, and parameters from
the address bar. Furthermore, in the previous
lesson, we created the parent of all
controllers.
Now we can make it so that the method of the controller,
whose data is contained in our variable $track, is called.
A special class, Dispatcher, will handle this.
The dispatcher will receive an object of the Track class
and, based on its data, create an object of the specified
class, call the method of that class, passing
parameters to this method.
Let's add the dispatcher call to the file index.php:
<?php
namespace Core;
error_reporting(E_ALL);
ini_set('display_errors', 'on');
spl_autoload_register(function($class) {
// your autoload implementation
});
$routes = require $_SERVER['DOCUMENT_ROOT'] . '/project/config/routes.php';
$track = ( new Router ) -> getTrack($routes, $_SERVER['REQUEST_URI']);
// Dispatcher call:
$page = ( new Dispatcher ) -> getPage($track);
?>
Calling the getPage method of our dispatcher
will call the controller's render method
and return what that method call returned.
As you already know from the previous lesson, the
controller's render method returns an object
of the Page class.
Here is the stub of our Dispatcher class:
<?php
namespace Core;
class Dispatcher
{
public function getPage(Track $track)
{
...code
return controller -> render(parameters);
}
}
?>
Using my stub, implement the described
class Dispatcher. Test its operation.
If you have difficulties, look at the source code
in the files of my made educational framework.