How to pass controller variable to view

Asked

Viewed 1,440 times

3

Hi, I made a 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; ?>
  • Transform $user in class attribute Home and add a method function getUser() giving a return $this->user;

  • Then call the method in the view, after instantiating Home, with a simple echo $HomeObj->getUser();

  • could do that in my code? I just didn’t understand your logic

  • loadView() only makes a file include?

  • @rray yes, a require (has $data = null in function parameters)

  • raisin $row on the index, $this->loadView('home/index', $row);

  • 2

    Not clear enough. Is this a known framework? Do you have documentation? Or did you create the framework? Normally you should have some compiler for view templates. View helpers should usually have a variable signature method.. is by this method that you pass the controller/model data to the view.

  • 1

    I created the framework, and there is no documentation.

Show 3 more comments

2 answers

2


I ended up solving it as follows: I turned the $data parameter into an 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';
}

0

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

This will prevent access to variables $this, I also recommend using the type induction (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 view access will look like this (I believe):

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

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

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

<?php echo $user; ?>

Browser other questions tagged

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