【问题标题】:serializing objects in php to use in sessions在 php 中序列化对象以在会话中使用
【发布时间】:2014-07-07 06:18:12
【问题描述】:

我正在尝试序列化我的对象“ShoppingCart.php”和对象“Item.php”,但我不能,而且我不知道还能做什么,所以我把我的代码留在这里看看是否有人可以帮我。我的问题是对象 ShoppingCart.php 有一个存储项目数组的属性,我不确定我是否很好地序列化/反序列化对象。

我已经总结了我的类,所以它们不包括所有方法,但它们仍然显示了最多的代表。如果还不够清楚,我会再次更改它。

提前致谢:

<?php 

class ShoppingCart implements Iterator, Countable,Serializable {

    // Array stores the list of items in the cart:
    protected $items = array();

    // For tracking iterations:
    protected $position = 0;

    // For storing the IDs, as a convenience:
    protected $ids = array();

    // Constructor just sets the object up for usage:
    function __construct() {
        $this->items = array();
        $this->ids = array();
    }


    // Adds a new item to the cart:
    public function addItem(Item $item) {

        // Need the item id:
        $id = $item->getId();

        // Throw an exception if there's no id:
        if (!$id) throw new Exception('The cart requires items with unique ID values.');

        // Add or update:
        if (isset($this->items[$id])) {
            $this->updateItem($item, $this->items[$id]['qty'] + 1);
        } else {
            $this->items[$id] = array('item' => $item, 'qty' => 1);
            $this->ids[] = $id; // Store the id, too!
        }

    } // End of addItem() method.

    // Changes an item already in the cart:
    public function updateItem(Item $item, $qty) {

        // Need the unique item id:
        $id = $item->getId();

        // Delete or update accordingly:
        if ($qty === 0) {
            $this->deleteItem($item);
        } elseif ( ($qty > 0) && ($qty != $this->items[$id]['qty'])) {
            $this->items[$id]['qty'] = $qty;
        }

    } // End of updateItem() method.

    // Removes an item from the cart:
    public function deleteItem(Item $item) {

        // Need the unique item id:
        $id = $item->getId();

        // Remove it:
        if (isset($this->items[$id])) {
            unset($this->items[$id]);

            // Remove the stored id, too:
            $index = array_search($id, $this->ids);
            unset($this->ids[$index]);

            // Recreate that array to prevent holes:
            $this->ids = array_values($this->ids);

        }

    } // End of deleteItem() method.



    public function serialize(){

        foreach ($this->items as $clave => $item)
            $listaItems[$clave]=serialize($this->items['item'][$clave]);

        foreach ($this-items as $clave=>$valor)
            $listaCantidades[$clave]=$this->items['qty'][$clave];

        return 
            array(
                'items'=>$listaItems,
                'qty'=>$listaCantidades,
                'ids'=>$this->ids,
                );

    }

    public function unserialize($data){
        //$data=unserialize($data);

        $this->items=array(
            'items'=>$data['items'],
            'qty'=>$data['qty']
            );
        $this->ids=$data['ids'];

        foreach($this->items as $clave => $item)
            $this->items[$clave]=unserialize($item);
    }

} // End of ShoppingCart class.


<?php # Item.php

// This is a sample Item class. 
// This class could be extended by individual applications.
class Item implements Serializable{

    // Item attributes are all protected:
    protected $id;
    protected $name;
    protected $price;
    protected $description;

    public function serialize(){
        return serialize(
            array(
                'id'=>$this->id,
                'name'=>$this->name,
                'price'=>$this->price,              
                'description'=>$this->description           
            )

        );
    }

    public function unserialize($data){
        $data=unserialize($data);

        $this->id=$data['id'];
        $this->name=$data['name'];
        $this->price=$data['price'];
        $this->description=$data['description'];    
    }

    // Constructor populates the attributes:
    public function __construct($id, $name, $price) {
        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
    }

    // Method that returns the ID:
    public function getId() {
        return $this->id;
    }

    // Method that returns the name:
    public function getName() {
        return $this->name;
    }

    // Method that returns the price:
    public function getPrice() {
        return $this->price;
    }

    public function getDescription() {
        return $this->description;
    }

    public function setDescription($descripcion){
        $this->description=$descripcion;
    }

} // End of Item class.

【问题讨论】:

  • 您应该删除所有不必要的代码并准确描述您的问题。如果您只想进行代码审查,请转到 codereview.stackexchange.com
  • 好的,谢谢你的建议,我刚刚编辑过,但我仍然包含一些方法,因为我很感兴趣,你可以看看数组是如何工作的。

标签: php session serialization


【解决方案1】:

您的直接问题是实现Serializable 的对象必须从serialise 方法返回一个序列化 字符串。目前,您正在返回一组数据。你应该这样做:

public function serialize() {
    ...

    return serialize(array(...));
}

您实际上在 Item 课程中正确地执行了此操作。但是,我不明白为什么您首先要手动序列化。您基本上是在复制 serialize() 的默认行为,而没有任何额外的好处。只需摆脱Serializable 接口及其实现和PHP 序列化的默认行为就可以为您服务。例如:

$_SESSION['cart'] = $myShoppingCart;

完成。在您的情况下,无需实现 serialize

【讨论】:

  • 不,仍然没有工作,也许我错了,但我知道你序列化和反序列化一个对象以持久化数据。我的问题是购物车使用了一个对象数组,所以我不知道如何序列化它。
  • 再说一次,我不太确定你为什么需要做一些特别的事情。请参阅3v4l.org/VtXgD,它无需任何特殊代码即可工作。
  • 没关系,我想我的问题是我读错了数组,我认为对象没有正确序列化。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2015-12-09
相关资源
最近更新 更多