How to inject a variable into a page that was required by a function

3

I'm having the following problem, I'm using an MVC template for a CMS in PHP study, however I'd like it to be possible to use themes, so I've created a configuration variable that stores the theme name for test , and when I use my controller to call my view , it looks like this:

$this->render('view_posts', $parametros);

In this function I pass the view that I'm going to use and vector $parametros , which contains page title, description, content, etc. My render () function looks like this:

private function render($view, $parametros)
{
  require_once(_APP_ROOT . '/view/' . $view.'.php');
}

If I try to get the $parametros vector in view_posts.php it works without problems, but as I said I wanted it to support themes, then in view_posts.php I have require_once with the theme name and corresponding page .

require_once(_APP_ROOT . '/tema/' . _TESTE_TEMA . 'index_view.php');

And in index_view.php of my theme it does not recognize the $parametros vector.

How can I solve this problem? I think it's an easy problem to solve but I'm already a bit blind on this project and can not find a solution.

One detail I'd like to cite is that I'm not using any framework , and I also do not want to use because it's a study CMS.

    
asked by anonymous 19.11.2015 / 11:36

2 answers

3

You can do this, and pass the parameters:

   class View
    {
        function render($file, $variables = [])
        {
            extract($variables);

            ob_start();
            include_once _APP_ROOT .
                         DIRECTORY_SEPARATOR .
                         'tema' . 
                         DIRECTORY_SEPARATOR . 
                         func_get_args(0) . '.php';
            $renderedView = ob_get_clean();
            return $renderedView;
        }
    }

    $view = new View();
    echo $view->render('view_posts', ['foo' => 'bar']);
    
19.11.2015 / 13:02
1

Ivan Ferrer's answer has helped a lot, but here's my solution to suit anybody else.

In my controller my render () function looks like this:

public function render()
    {   
        $template = new template(__DIR_MEU_template, __SITE_WWW);
        $view = new view($template);
        $view->render('index_view', ['output' => 'má oeeee' ]);
    }

And my class view

class view
{
    private $template;

    public function __construct($template)
    {
        $this->template = $template;
    }

    public function render($view, $vars = [])
    {
        require_once($this->template->get_diretorio() . $view . '.php');
    }
}

It's still extremely simple and I'm using constants to test, but this is logic, so I can call any variable that is passed to the view class in my theme.

Thanks for the answers.

    
19.11.2015 / 13:30