How to pass data to all views in a MVC pattern?

Asked

Viewed 1,095 times

2

I’m building a small MVC application with PHP, following directory structure:

  • controllers/ (Controller files)

  • views/ (View files)

In each controller, I pass an instance of the Object VIEW with an array of data to be able to use it in the view file, example:

New View('Busca','header', 'footer', $viewParams );

Note: these 2 parameters I passed (header and footer), will be included together from the view, example:

Include Header;    
Include Busca ( **a view que passei por parâmetro** );    
Include Footer;

So far so good, I can pass the data to any view, from your controller, but as I sliced my site with HEADER and FOOTER , and these files are not in the rule of my view which is to pick the VIEW files by folders, example:

Structure of the Directory

Views/Busca/    
     - Index.phtml

Views/Error/    
     - Index.phtml

Como HEADER e FOOTER, estão em:    
     - Views/Header.phtml    
     - Views/Footer.phtml

Only I need to change values dynamically in my header, the only way to do this is in all Controller, put the same code and pass parameter to my view, example:

BuscaAction()
{    
    $setParams = array('title_page' => 'Título do Site');
    $view = New view('Busca','header','footer',$setParams);    
    $view->render();    
}

ErrorAction(){    
    $setParams = array('title_page' => 'Título do Site');    
    $view = New view('Error','header','footer',$setParams);    
    $view->render();    
}

Instead, I would like to pass this information in a unique way that can dynamically change, as if it were a normal controller, go through the controller builder is a solution?

1 answer

1

Good, the problem you present seems to me easy to solve, the controllers in which you need to define a header and a footer just hardam a controller that has this data.

example:

<?php

class BaseController {
    protected $data = [ 
        'header' => 'views/header.php',
        'footer' => 'views/footer.php'
    ];

    function __construct() { }
}

class HomeController extends BaseController {

    function __construct() {
        parent::__construct();
        var_dump($this->data);
    }

}

new Homecontroller();

outputs:

array(2) {
  'header' =>
  string(16) "views/header.php"
  'footer' =>
  string(16) "views/footer.php"
}

However you can use my framework http://pedrosimoes79.github.io/silverbullet/, to do what you want, just create a Triade MVC that handles the header and footer and other layout details, and then call the controller/action in the view, without needing to get data in the main controller, ie, everything very well separated ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.