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

2

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

  • controllers /

  • views / (Views files)

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

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

Note: these 2 parameters that I have passed (header and footer), will be included together of 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 its controller, but how I made my site with HEADER and FOOTER, and these files are not in the rule of my view that is to get VIEW files by folders, for example:

Directory Structure

Views/Busca/    
     - Index.phtml

Views/Error/    
     - Index.phtml

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

I just need to change values dynamically in my header, the only way to do this is in every controller, put the same code and pass by 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 and can dynamically change, as if it were a normal controller, passing through the controller constructor is a solution?

    
asked by anonymous 26.04.2014 / 05:17

1 answer

1

Well, the problem that you present seems to me easy to solve, the controllers in which you need to define a header and a footer just need to work from 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 link , to do what you want, just create an MVC triad that deals with the header and footer and other layout details, and then call the controller / action in the view, without having to get data in the main controller, ie, all very well separated;)

    
26.04.2014 / 13:10