[英]Incomplete PHP class when serializing object in sessions
我正在制作购物车(购物车模型)。 其中一个受保护的属性是“_items”,它包含一个 Product 对象数组。 它们(产品)都存储在数据库中以填充 session(使用 ZF、Zend_Session_SaveHandler_DbTable() 等)。
public function addItem(Model_Product $product, $qty)
{
$qty = (int) $qty;
$pId = $product->getId();
if ($qty > 0) {
$this->_items[$pId] = array('product' => $product, 'qty' => $qty);
} else {
// if the quantity is zero (or less), remove item from stack
unset($this->_items[$pId]);
}
// add new info to session
$this->persist();
}
在 controller 中,我使用 ProductMapper 从 DB 中获取一个 Product obj 并将其提供给“addItem()”:
$product1 = $prodMapper->getProductByName('cap');
$this->_cart->addItem($product1, 2);
getProductByName()
返回一个新的填充 Model_Product object。
我通常得到
Please ensure that the class definition "Model_Product" of the object you are trying to operate on was loaded _before_...
错误消息,session 转储显然显示
['__PHP_Incomplete_Class_Name'] => 'Model_Product'
我知道“在序列化之前声明 class”。 我的问题是:我如何在addItem()
中声明 Product class ,如果它首先被注入(第一个参数)? 新声明(如new Model_Product()
)不会覆盖addItem()
中的参数(原始对象)吗? 我必须再次在购物车 model 中声明它吗?
此外,如果我在购物车中重新声明它,我肯定会得到一个Cannot redeclare class Model_Product
。
在 ZF 的引导程序中,session 在自动加载之前启动。
/**
* Make XXX_* classes available
*/
protected function _initAutoloaders()
{
$loader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'XXX',
'basePath' => APPLICATION_PATH
));
}
public function _initSession()
{
$config = $this->_config->custom->session;
/**
* For other settings, see the link below:
* http://framework.zend.com/manual/en/zend.session.global_session_management.html
*/
$sessionOptions = array(
'name' => $config->name,
'gc_maxlifetime' => $config->ttl,
'use_only_cookies' => $config->onlyCookies,
// 'strict' => true,
// 'path' => '/',
);
// store session info in DB
$sessDbConfig = array(
'name' => 'xxx_session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);
Zend_Session::setOptions($sessionOptions);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($sessDbConfig));
Zend_Session::start();
}
当我遇到我所说的错误时,方法声明是相反的:首先是_initSession()
,然后是_initAutoloaders()
——这就是 ZF 处理它们的确切顺序。
我将进行更多测试,但这似乎可行(并且合乎逻辑)。 感谢您的所有建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.