How to pass controller variable to view [closed]

3

Hello, I did an mvc application but I'm having trouble passing a controller variable to the view. My codes:

class Home extends Controller {
    public function index() {
        $user = $this->loadModel('usersModel');
        $row = $user->getUserData(Session::get('user_id'));

        $this->loadView('_templates/header');
        $this->loadView('home/index');
        $this->loadView('_templates/footer');
    }
}

View:

<?php echo $user; ?>
    
asked by anonymous 20.12.2015 / 00:43

2 answers

2

I just solved the following: I changed the parameter $ data into object, so I was able to pass the user object

public function loadView($view, $data = null) {

    if($data) {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }

    require APP . 'view/' . $view . '.php';
}
    
20.12.2015 / 18:59
0

You can use extract combined with func_get_arg() that looks similar to some popular frameworks and use an anonymous function (requires php5.3) to avoid accessing the class scope, as in this answer:

This will prevent access to $this variables, so I recommend that you also use Type Hinting )

public function loadView($view, array $data = null)
{
    $load = function ($data)
    {
         if (empty($data) === false) {
              extract(func_get_arg(0));
         }

         require APP . 'view/' . $view . '.php';
    };

    $load($data);
    $load = $data = NULL;
}

The access in the view will look like this (I believe):

$row = $user->getUserData(Session::get('user_id'));

$this->loadView('home/index', $row);

And in home/index.php and variable access will be something like (without the need of $this ):

<?php echo $user; ?>
    
20.12.2015 / 20:30