将对象保存到会话 - 如何像以前一样从会话中获取我的对象?

Saving object to a session - How do I fetch my object from the session as it was before?

我正在将具有一些变量和方法的客户 class 保存到会话中。

从会话中取回它时,我如何设法让它的所有方法都起作用? (尽可能像原件一样)

我目前所做的是:

<?php
namespace MyApp\Models;
use MyApp\Core\Database;
use MyApp\Helpers\Session;
use MyApp\Core\Config;

class Customer {

    private $db;

    public $host;

    public $dbName; 

    public $type;


    public function __construct($customerName = NULL)
    {
        # Get database instance
        $this->db = Database::getInstance();

        # If customer name passed as a variable 
        if ( $customerName ) {

            # Get Customer data from db
            $data = $this->customerDataByName($customerName);

            if ($data) {
                # Set data to $this Obj
                $this->setCustomerData($data['db_host'], $data['db_name'], $data['system_type']);
                # Set $this Obj to Session
                $this->setCustomerToSession();
            } else {
                return false; 
            }
        } 
    }


    public function setCustomerData($host, $dbName, $type)
    {
        # Set customer host in object
        $this->host     = $host;
        # Set customer name in object
        $this->dbName   = $dbName;
        # Set customer type in object
        $this->type     = $type;
    }


    public function setCustomerToSession()
    {
        Session::put(Config::$customer, $this); 
    }


    public function customerDataByName($customer_name) 
    {
        return $this->db->row("SELECT `db_name`, `db_host`, `system_type` FROM customers WHERE customer_name = :customer_name", array('customer_name' => $customer_name));
    }



    public function __sleep()
    {
        return array('host', 'dbName', 'type', 'customerDataByName()', 'setCustomerData()' );
    }

    public function __wakeup()
    {
        $this->db = Database::getInstance();
    }

}

"host"、"dbName" 和 "type" 使用 __sleep() 方法正确恢复,我尝试以几种不同的方式添加函数,但没有成功.. 我希望它也能够连接到数据库。

并尝试使用其他方法:

public function setCustomerToSession()
{
    $serialized = serialize($this);
    Session::put(Config::$customer, $serialized); 
}

没有__wakup__sleep,然后尝试:

$a = unserialize($_SESSION['customer']);
var_dump($a);

并收到此错误:

PHP Fatal error: Uncaught PDOException: You cannot serialize or unserialize PDO instances in...

指向$serialized = serialize($this);

您应该使用函数 serialize() 来 returns 一个包含值的字节流表示的字符串,相反您可以使用 unserialize()。因为你不能在 PHP SESSION.

中存储对象

代码应该是,

session_start();

$a = your_object;
$b = serialize($a);

$_SESSION["serialized_data"] = $b; 
# To store in Session

$unserialized_data = unserialize($_SESSION["serialized_data"]); 
# To get from Session as Object