jlmmns
jlmmns

Reputation: 845

PHP MVC - Where and when to instantiate and pass the User object for use in all views?

After authentication, where and when do I instantiate and pass the User object, to use in all my views?

My logic is to create a new User in my Login 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?

I don't like to use static methods, like I've done with my Auth and Session class. For these two little classes, it's OK to use static methods, right?

Login controller:

class Login extends Controller {

    private $username;
    private $password;
    private $response;
    private $user;
    private $errors;

    public function __construct() {
        parent::__construct();
        $this->errors = array();
    }

    public function index() {
        $this->view->render('login/index');
    }

    public function submit() {
        $this->username = trim($_POST['username']);
        $this->password = trim($_POST['password']);

        try {
            if (!$this->isLoginValid())
                throw new Exception('invalid username or password');

            header('Location: '.URL_SSL.'dashboard');
        }
        catch (Exception $e) {
            $this->errors[] = $e->getMessage();
        }
    }

    private function isLoginValid() {
        $this->response = $this->model->submit($this->username);

        if ($this->response) {
            require APP.'lib/password_compat/password.php';

            $this->user = $this->response[0];

            if (password_verify($this->password, $this->user->password)) {
                $this->registerSessions();
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }

    private function registerSessions() {
        Session::init();
        Session::set('loggedIn', true);
    }

}

Dashboard controller:

class Dashboard extends Controller {

    public function __construct() {
        Auth::checkLogin();   // Checks the 'loggedIn' session
        parent::__construct();
    }

    public function index() {
        $this->view->setPageTitle('Dashboard');
        $this->view->render('dashboard/index');
    }

}

Upvotes: 0

Views: 1382

Answers (1)

rinchik
rinchik

Reputation: 2670

You can just store userId in a session and use it anywhere to create a user object.

And then something like:

class Dashboard extends Controller {

public function __construct() {
    Auth::checkLogin();   // Checks the 'loggedIn' session
    parent::__construct();
}

public function index() {
    $this->view->setUserDataArra((array) \Path\To\User\Class::GetUserObjectbyId($_SESSION['userId']));
    $this->view->setPageTitle('Dashboard');
    $this->view->render('dashboard/index');
}
}

Or you can define $userObj in controller and populate it after login.

Upvotes: 2

Related Questions