Controllers in Your Own MVC Framework in PHP
As you already know, all controllers in our
framework have a render method that
needs to be called to send data to the view.
Our custom controllers inherit this method
from the parent class Controller,
located in the core. Let's create this class:
<?php
namespace Core;
class Controller
{
protected function render($view, $data) {
}
}
?>
As you can see, the render method
takes the name of the view and the data for
display as parameters. Let this method return
an object of a special class Page, which
will contain information about the view
for the controller action. This class
will contain the view name, data,
as well as the page title and the name of the site layout file:
<?php
namespace Core;
class Page
{
private $layout;
private $title;
private $view;
private $data;
public function __construct($layout, $title, $view, $data)
{
$this->layout = $layout;
$this->title = $title;
$this->view = $view;
$this->data = $data;
}
public function __get($property)
{
return $this->$property;
}
}
?>
Then the code for our render method will
look like this:
<?php
namespace Core;
class Controller
{
protected $layout = 'default';
protected function render($view, $data) {
return new Page($this->layout, $this->title, $view, $data);
}
}
?>
Let me explain what is happening here. The view name
and data come as method parameters. However,
the page title is also set in the custom
controller - by writing to the title
property. This means that $this->title
will contain the title that we will pass to
the constructor of the Page class.
There are also nuances with the layout. As you know,
our framework uses the layout from the file
default.php. In fact, each
action can have a different layout. To do
this, the action itself needs to write a different layout name to the layout
property.
How this is achieved: our parent controller
has a layout property, which by default
has the value 'default.php'. This
will be the default layout. However, if
the action of the custom controller overrides
the value of the layout property, then the layout
will be different.
Copy the code of my Controller class and place it in the file
/core/Controller.php.
Copy the code of my Page class and
place it in the file /core/Page.php.