身份验证后,我在何时何地实例化并传递 User 对象以在我的所有视图中使用?
new User
我的逻辑是在身份验证后在我的Login
控制器中创建一个。但是,在重定向到受保护的仪表板页面后,如何在我的所有视图中使用该对象及其数据?
我不喜欢使用静态方法,就像我对我的Auth
和Session
班级所做的那样。对于这两个小类,使用静态方法就可以了,对吧?
登录控制器:
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);
}
}
仪表板控制器:
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');
}
}