【问题标题】:Where should I put new Session in my project?我应该在我的项目中将新会话放在哪里?
【发布时间】:2014-09-06 10:48:11
【问题描述】:

我正在创建发布公告项目。 在这里我创建Session class 来管理session

我的index.php

$bulletin = new Controller_Bulletin();
$bulletin->setParams(array_merge($_GET, $_POST));
$bulletin->execute('index'); // Execute index action

我的Controller_Bulletin.php

class Controller_Bulletin extends Controller_Base
{
  ...
  public function index() // My index action
  {
    // Render the index html
    $this->render('bulletin/index.php', get_defined_vars());
  }

  public function insert() // My insert action
  {
    ...
  }
  ...
}

我的Session class

class Session
{
  public function __construct()
  {
    session_start();
  }
  ...
}

我需要在每个动作中加载 Session 类。 示例:索引、插入等。 但是当我在每个动作中都加上$session = new Session(); 时。 导师说不好。 也许是因为我在每个动作中都重复了它。 Controller_Bulletin class中的示例

public function index()
{
  $session = new Session();
  ...
}

public function insert()
{
  $session = new Session();
  ...
}

我仍然不擅长 OOP。 有人可以告诉我应该在哪里调用会话对象吗? 如果我的问题还不清楚,请告诉我。

【问题讨论】:

    标签: php class session


    【解决方案1】:

    这样怎么样

    class Controller_Bulletin extends Controller_Base {
    
        protected $session;
    
        public function __construct() {
            parent::__construct();
            $this->session = new Session();
        }
    
        public function index() { // My index action
            // Render the index html
            // use $this->session here
            $this->render('bulletin/index.php', get_defined_vars());
        }
    
        public function insert() { // My insert action
            // use $this->session here
        }
    
    }
    

    【讨论】:

    • 我已经这么想了。也许我会尝试一下。我稍后会更新我的导师问题。
    【解决方案2】:

    您可以在每个操作中加载$session = new Session();。但为此,您必须对您的public function __construct() 进行一些小改动。将您的功能更改为

    public function __construct()
    {
    if(session_id() === ""){
         session_start();
    }
    }
    

    这将检查之前是否启动过任何会话。如果是这样,它不会重新开始,也不会出错。

    【讨论】:

    • 我已经上课了 session_start();所以我认为做 session_start() 是没有意义的。
    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 2020-09-30
    相关资源
    最近更新 更多