我正在编写一个PHP程序,它执行SOAP请求,并返回一个Object。我需要编写一个函数,它从这个Object获取数据并以各种方式使用它,但是如果对象中的数据的SOAP请求已经驻留,我不希望它每次都执行SOAP请求。 / p>
伪代码示例:
$price = GetPartPrice("1234");
function GetPartPrice($part_number) {
If Parts_List_Object not found then do SOAP request to get Parts_List_Object.
}
我看到的问题是,如果Parts_List_Object已经存在,我不知道在哪里或如何存储。我是否需要设置一些东西来使得从SOAP / JSON请求全局请求的StdClass对象,或者有更好的方法来完成所有这些操作吗?谢谢!
答案 0 :(得分:0)
一种方法是构建这些对象的注册表,在这些对象中存储您获取的对象并查找所需的对象。这允许您只是获取对已加载的实例的引用。一个非常基本的例子:
class PartListRegistry {
private static $list = array();
// After you do the SOAP request, call this to save a reference to the object
public static function addPartObject($key, $obj) {
self::$list[$key] = $obj;
}
// Call this to see if the object exists already
public static function getPartObject($key) {
if (isset(self::$list[$key])) {
return self::$list[$key];
}
return null;
}
}
function GetPartPrice($part_number) {
$part = PartListRegistry::getPartObject($part_number);
if ($part === null) {
$part = .... // Do your SOAP request here
// Save a reference to the object when you're done
PartListregistry::addPartObject($part_num, $part);
}
// Do your stuff with the part ....
}