0

身份验证后,我在何时何地实例化并传递 User 对象以在我的所有视图中使用?

new User我的逻辑是在身份验证后在我的Login控制器中创建一个。但是,在重定向到受保护的仪表板页面后,如何在我的所有视图中使用该对象及其数据?

我不喜欢使用静态方法,就像我对我的AuthSession班级所做的那样。对于这两个小类,使用静态方法就可以了,对吧?

登录控制器:

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');
    }

}
4

1 回答 1

2

您可以只存储userId在会话中并在任何地方使用它来创建用户对象。

然后是这样的:

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');
}
}

或者您可以在控制器中定义 $userObj 并在登录后填充它。

于 2013-03-27T20:27:45.550 回答