簡體   English   中英

在控制器中使$ _SESSION可用

[英]Making $_SESSION available in controllers

我試圖讓我的框架的控制器從頭開始編寫$_SESSION全局。 它不是MVC,表示層由兩個具有多個子類的父類組成。

沒有詳細介紹,我的視圖將在class Template中呈現

class Template{

    protected $_controller;
    protected $_action;

    function __construct($controller,$action) {
        $this->_controller = $controller;
        $this->_action = $action;
    }

    function render(){
        if (file_exists(APP_ROOT . DS . 'app' . DS . 'view' . DS . $this->_controller . DS . $this->_action . '.php')) {
            include (APP_ROOT . DS . 'app' . DS . 'view' . DS . $this->_controller . DS . $this->_action . '.php');
        }
    }

}

然后我在構造函數中實例化class Template后,在我父控制器內的析構函數中調用Template::render() 所有課程都是自動加載的。

class CoreController {

    protected $_controller;
    protected $_action;
    protected $_template;

    function __construct($controller, $action) {
        $this->_controller = ucfirst($controller);
        $this->_action = $action;

        $this->_template = new Template($controller,$action);
    }

    function __destruct() {
        $this->_template->render();
    }
} 

我的問題是如何在CoreController中使$_SESSION可用,以及何時在關機序列中可用? 我試過直接在CoreController中以及在Template::render()調用它,並且總是得到未定義的變量警告,但是在我的視圖中定義$_SESSION有效的。 這背后的原因是我想根據會話ID是否設置來設置某些變量,並且我希望將大多數表示邏輯保留在我的控制器中。 提前致謝。

會話是一種存儲形式。 這意味着它應該只在模型層中深入使用。

在表示層中操作$_SESSION與控制器和/或視圖中的擰緊SQL相當。 你將消除SoC的最后痕跡......雖然你已經通過實現像“ViewController”怪物這樣的Rails來實現它。

您應該使用類似於sql的類似映射器,而不是將存儲邏輯泄漏到表示層中。

來自模型層的一些服務

public function identify( $parameters )
{

    $user = $this->domainObjectFacctory->create('user');
    $mapper = $this->mapperFactory->create('session');

    if ( $mapper->fetch($user, 'uid') === false )
    {
        $mapper = $this->mapperFactory->create('user');
        $user->setUsername($parameters['login']);
        $user->setPassword($parameters['pass']);

        $mapper->fetch($user);
    }

    $this->currentUser = $user->isValid()
                       ? $user
                       : null;
}

控制器僅與服務交互

public function postLogin( $request )
{
    $auth = $this->serviceFactory->create('recognition');
    $auth->identify([
        'login' => $request->getParameter('username'),
        'pass'  => $request->getParameter('password'),
        ]);
}

服務工廠將注入控制器(和附帶的視圖)構造函數中。

注意:上面的代碼僅用於說明要點,不應復制粘貼或以其他方式嫁接到生產代碼上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM