Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Load your view automatically
  • Instead of defining and loading your view in every controller like:
    <?php
    
    class Controller_Home extends \Controller_Template
    {
    
        public function action_index()
        {
            $this->template->body = \View::forge('home/index', $this->data);
        }
    
        public function action_subscribe()
        {
            $this->template->body = \View::forge('home/subscribe', $this->data);
        }
    
    ?>
    

    This will be sufficient. It loads the expected view, based on the current controller and method.
    <?php
    
    class Controller_Home extends \Controller_Base
    {
    
        public function action_index()
        {
            //loads views/home/index.php as body-part of the template
        }
    
        public function action_subscribe()
        {
            //loads views/home/subscribe.php as body-part of the template
        }
    
        public function action_otherpage()
        {
            $this->view = 'an/other/view.php';
            //loads views/an/other/view.php as body-part of the template
        }
    
    ?>
    

    How to achieve this? Make a base controller, from which you extend every controller you make for your website:
    <?php
    
    abstract class Controller_Base extends \Controller_Template
    {
    
     protected $view = '';
     protected $data = array();
    
     public function after($response)
     {
      if(empty($this->view))
      {
       $class = \Str::lower(substr(\Inflector::denamespace(\Request::active()->controller), 11));
       $method = \Request::active()->action;
       $this->view = "{$class}/{$method}";
      }
    
      $this->template->body = \View::forge($this->view, $this->data);
    
      parent::after($response);
     }
    
    }
    

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!