User Rating: 2 / 5

Star ActiveStar ActiveStar InactiveStar InactiveStar Inactive
 

The Controller is the "C" in MVC. The base controller is a simple abstract class that defines the structure of all controllers. By including the registry here, the registry is available to all class that extend from the base controller. An index() method has also been included in the base controller which means all controller classes that extend from it must have an index() method themselves.

Add this code to the controller.class.php file in the application directory.

<?php
Abstract Class baseController {
protected $registry;
function __construct($registry) {
   $this->registry = $registry;
}
abstract function index();
}
?>

Whilst we are in the controller creating mood, we can create an index controller and a blog controller. The index controller is the system default and it is from here that the first page is loaded. The blog controller is for an imaginary blog module. When the module is specified in the URL

http://www.example.com/blog

then the index method in the blog controller is called. A view method will also be created in the blog controller and when specified in the URL

http://www.example.com/blog/view

then the view method in the blog controller will be loaded. First lets see the index controller. This will reside in the controller directory


<?php
class indexController extends baseController {
public function index() {
$this->registry->template->welcome = 'Welcome to MindPHP.com';
$this->registry->template->show('index');
}
}
?>

The indexController class above shows that the indexController extends the baseController class, thereby making the registry available to it without the need for global variables. The indexController class also contains the mandatory index() method that ll controllers must have. Within itn index() method a variable named "welcome" is set in the registry. This variable is available to the template when it is loaded via the template->show() method.

The blogController class follows the same format but has one small addition, a view() method. The view() method is an example of how a method other than the index() method may be called. The view method is loaded view URL http://www.example.com/blog/view

<?php
Class blogController Extends baseController {
public function index(){
$this->registry->template->blog_heading = 'This is the blog index';
$this->registry->template->show('blog_index');
}
public function view() {
$this->registry->template->blog_heading = 'This is the blog heading';
$this->registry->template->blog_content = 'This is the blog content';
$this->registry->template->show('blog_view');
}
}
?>