php memcached存储对象,从memcached获取对象并在PHP中设置为self

该博客讨论了在PHP中如何从Memcached缓存或数据库中获取数据并填充到对象中。当从缓存中获取数据成功时,通过直接赋值或使用foreach循环来设置对象属性。如果数据不在缓存中,则从数据库查询并使用PDO的fetch_class或fetch_into方法将结果映射到当前对象。同时,提出了使用静态方法作为替代方案来创建和返回对象实例。
摘要由CSDN通过智能技术生成

你的问题和后续评论的措辞有些含糊不清,但他们仍然指出我的方向如下:

public function __construct($id) {

global $pdo, $memcached;

$data = $memcached->get($id);

if($memcached->getResultCode() == Memcached::RES_SUCCESS) {

// this is not currently allowed in PHP

$this = $data;

// this should be your fix

foreach($data AS $key => $value) {

$this->$key = $value;

}

// or this

foreach($this AS $key => $value) {

$this->$key = $data[$key];

}

// the difference between the fixes above is that

// the second is strictly limited to values defined

// by the class (current object)

}

else {

$pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?');

if($pdos) {

// this is not allowed in PHP

$pdos->execute(array(intval($id)));

$this = $pdos->fetch(PDO::FETCH_CLASS, get_class($this));

// all of this should work fine and is allowed

$pdos->setFetchMode(PDO::FETCH_INTO, $this);

$pdos->execute(array(intval($id)));

$pdos->fetch(PDO::FETCH_INTO);

}

}

}但不幸的是,PHP不允许在内部覆盖$ this的值(在它自己的方法调用中),因此可以做的另一种方法是使用静态方法。

public static function getByID($id) {

global $pdo, $memcached;

$data = $memcached->get($id);

if($memcached->getResultCode() == Memcached::RES_SUCCESS) {

// this will work if your objects construct has a

// foreach similar to the ones presented above

$result = new self($data);

// or if you don't want to write a foreach in

// the construct you can have it here

foreach($data AS $key => $value) {

$this->$key = $value;

}

// or here

foreach($this AS $key => $value) {

$this->$key = $data[$key];

}

}

else {

$pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?');

if($pdos) {

// either of these should work

$pdos->execute(array(intval($id)));

$result = $pdos->fetch(PDO::FETCH_CLASS, get_class($this));

// either of these should work

$result = new self;

$pdos->setFetchMode(PDO::FETCH_INTO, $result);

$pdos->execute(array(intval($id)));

$pdos->fetch(PDO::FETCH_INTO);

}

}

return($result);

}用法语法为MyClass::get($some_id)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值