PHP MVC -何时何地实例化并传递User对象以便在所有视图中使用



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

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

我不喜欢使用静态方法,就像我在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');
    }
}

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

然后像这样:

class Dashboard extends Controller {
public function __construct() {
    Auth::checkLogin();   // Checks the 'loggedIn' session
    parent::__construct();
}
public function index() {
    $this->view->setUserDataArra((array) PathToUserClass::GetUserObjectbyId($_SESSION['userId']));
    $this->view->setPageTitle('Dashboard');
    $this->view->render('dashboard/index');
}
}

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

最新更新