title: PHP MVC - Where and when to instantiate and pass the User object for use in all views?
body: <p>After authentication, where and when do I instantiate and pass the User object, to use in all my views?</p>
  
  <p>My logic is to create a <code>new User</code> in my <code>Login</code> controller, after authentication. But how do I use that object and its data in all of my views, after being redirected to the secured dashboard page?</p>
  
  <p>I don't like to use static methods, like I've done with my <code>Auth</code> and <code>Session</code> class.
  For these two little classes, it's OK to use static methods, right?</p>
  
  <p><strong>Login controller:</strong></p>
  
  <pre><code>class Login extends Controller {
  
      private $username;
      private $password;
      private $response;
      private $user;
      private $errors;
  
      public function __construct() {
          parent::__construct();
          $this-&gt;errors = array();
      }
  
      public function index() {
          $this-&gt;view-&gt;render('login/index');
      }
  
      public function submit() {
          $this-&gt;username = trim($_POST['username']);
          $this-&gt;password = trim($_POST['password']);
  
          try {
              if (!$this-&gt;isLoginValid())
                  throw new Exception('invalid username or password');
  
              header('Location: '.URL_SSL.'dashboard');
          }
          catch (Exception $e) {
              $this-&gt;errors[] = $e-&gt;getMessage();
          }
      }
  
      private function isLoginValid() {
          $this-&gt;response = $this-&gt;model-&gt;submit($this-&gt;username);
  
          if ($this-&gt;response) {
              require APP.'lib/password_compat/password.php';
  
              $this-&gt;user = $this-&gt;response[0];
  
              if (password_verify($this-&gt;password, $this-&gt;user-&gt;password)) {
                  $this-&gt;registerSessions();
                  return true;
              }
              else {
                  return false;
              }
          }
          else {
              return false;
          }
      }
  
      private function registerSessions() {
          Session::init();
          Session::set('loggedIn', true);
      }
  
  }
  </code></pre>
  
  <p><strong>Dashboard controller:</strong></p>
  
  <pre><code>class Dashboard extends Controller {
  
      public function __construct() {
          Auth::checkLogin();   // Checks the 'loggedIn' session
          parent::__construct();
      }
  
      public function index() {
          $this-&gt;view-&gt;setPageTitle('Dashboard');
          $this-&gt;view-&gt;render('dashboard/index');
      }
  
  }
  </code></pre>