6.2. Controller inheritance - notafrancescodavid/webmvcframework GitHub Wiki

Another important software engineering principle, widely used in WebMVC, is software reuse. The reuse of framework classes in implicit in the sense that a programmer can take advantage of functionalities provided by the framework. There is, however, the opportunity for software reuse also when the programmer design and implement code that can be used more than once. In the next example, we show the feature of controller inheritance that can be interpreted as a form of reuse from the father controller to the child controller in order to augment the child capabilities. We start from the dynamic block example presented in section 3.2.using a richer template and managing the user interaction so that a list of people can be hidden or visualized. We introduce the template block_extended.html.tpl and the controller BlockExtended; the classes Block model, Block view, and Block control remain the same as previously described, and are used here to run the controller inheritance example. The HTML file contains Bootstrap code to improve the graphical aspect of the presentation. In order to understand how the controller inheritance can be implemented, we first focus on the body of the HTML file and, in particular, on the tree blocks therein contained: UserLIstMessage, ContentUser, and Users.

<?php
    
namespace controllers;

use framework\Controller;
use models\UserList as UserListModel;
use views\UserList as UserListView;

class UserList extends Controller
{
     public function __construct(View $view=null, Model $model=null) {
        $this->view = empty($view) ? $this->getView() : $view;
        $this->model = empty($model) ? $this->getModel() : $model;
        parent::__construct($this->view,$this->model);
     }

    protected function autorun ($parameters=null) { 
      $userList = $this->model->getUsers();
      $this->view->setUserList($userList);
    }

    public function getView() {
        $view = new UserListView("/user_list");
        return $view;
    }

    public function getModel() {
        $model = new UserListModel();
        return $model;
    }
}

xxx

<?php

namespace controllers;

use framework\Controller;
use models\UserList as UserListModel;
use views\UserList as UserListView;

class ToggleUserList extends UserList

{	
  protected function autorun($parameters = null) {
	  $this->view = new UserListView("/toggle_user_list");
      $this->model = new UserListModel;
      parent::autorun();
	  
	 $this->view->hide("Warning");
  }
 	  
  public function hideUserList(){
	  $this->view = new UserListView("/toggle_user_list");
      $this->view->hide("UserList");
      $this->render();
  }
	
  public function hideContent() {
	  $this->view = new UserListView("/toggle_user_list");
	  $this->view->hide("ExampleDescription");
      $this->view->hide("Warning");
      $this->view->hide("UserList");
      $this->render();
  }
}