FuelPHP - Presenters



FuelPHP provides an additional layer after the controller to generate views. Once the controller processes the input and is done with the business logic, it sends the control to the Presenter, which takes care of the extra logic such as fetching data from the database, setting view data, etc., and then, calls the View object.

We can render the views using the Presenter class as follows −

fuel/app/classes/controller/employee.php

public Controller_Employee extends Controller { 
   public function action_welcome() { 
      return Presenter::forge('employee/hello'); 
   } 
}

The default location of presenter class is fuel/app/classes/presenter/. Following is a simple example.

fuel/app/classes/presenter/employee/hello.php

<?php  
   class Presenter_Employee_Hello extends Presenter { 
      public function view() { 
         $this->name = Request::active()->param('name', 'World'); 
      } 
   } 

The view file of the above presenter class resolves to employee/hello.php relative to the views folder, which is as specified.

fuel/app/views/employee/hello.php

<h3>Hi, <?php echo $name; ?></h3> 

Finally, change the route to match the employee's welcome action, shown as follows −

fuel/app/config/routes.php

'employee/hello(/:name)?' => array('employee/welcome', 'name' => 'hello'), 

Now, requesting the URL, http://localhost:8080/employee/hello/Jon renders the following result.

Result

Presenter View
Advertisements