Base Controller

We will define base Controller class , where we pass entire container to base Controller class that can be access by all sub class controller of Base Controller.

Step 1: Create a Base Controller
In app/Controllers/Controller.php we will create base controller name as Controller and add following code.

namespace App\Controllers;

class Controller {

    protected $container;

    public function __construct($container){
        $this->container = $container;

Accessing property from this methods is not best practice but we can used it for rapid prototyping of our project.
    public function __get($property) {  
        if ( $this->container->{$property}){
            return $this->container->{$property};

In Base controller constructor we are passing the container, we are using __get($property) method to access container property in base class. We don’t have to define

Step 2: In bootstrap/app.php we will modified container->view to $container in HomeController as view is already attach container in app.php

$container['HomeController'] = function($container) {
    return new \App\Controllers\HomeController($container);

Step 3: Now in app/Controller/HomeController we can extend Base Controller and can access view through container from Base Controller
return $this->container->view->render($res, ‘home.twig’);

We can access view without container in HomeController, for that we have to define
public function __get($property) {}
method in base Controller, this will return any property that we want to access, in our case we can access view directly from homeController without container. Dumping the property argument will return error with view object.


namespace App\Controllers;

use Slim\Views\Twig as View;

class HomeController extends Controller {

    public function index($req, $res){
        return $this->view->render($res, 'home.twig');