我有一个需要使用CURL的RESTful应用程序接口。我已经创建了一个包装类,它有一个带有CURL代码的静态函数。
class ApiInvoke
{
public static function execute($username, $password, $endpoint, $data = array(), $options = array())
{
//Rest of the CURL code goes here.....
}
}
我创建了一个类,在这个类中,我调用静态APIInvokve类方法来实际执行API调用。下面是上面ApiInvoke类的消费者类。
需要"api_invoke.php“
class FlowgearConnect
{
//Properties go gere
public function getResults($model, $workflow, $data)
{
$endpoint = $this->getEndpoint($model, $workflow);
$results = array();
if(!is_null($endpoint)){
$results = ApiInvoke::execute('username', 'password', $endpoint, $data array('timeout' => 30));
}
return $results;
}
//....
}
然后我有一个ParentClass类,它创建了一个FlowgearConnect对象的实例,使其可用于子类。但是,所有的子类都是在同一个父类中处理的。
class ParentClass
{
private $Flowgear;
public function init()
{
$this->Flowgear = new FlowGearConnect(); //Assuming it has been required somewhere
}
}
然后我们可能会有ChildClassA和ChildClassB,它扩展了ParentClass。通过子类的变量扩展父类,它们已经可以访问$this->Flowgear对象的实例,因为下面是如何使用FlowgearConnect类的:
class ChildClassA
{
public function getResults()
{
$results = $this->Flowgear->getResults('child_a', 'latestEvents', array());
}
}
ChildClassB具有完全相同的功能,或者更确切地说,除了它可能负责获取订单列表之外。
下面描述了如何在父类中处理这些子类:
//A function inside the ParentClass to process ChildClassA and ChildClassB
public function processModules()
{
$modules = $request->getModules();
foreach($modules as $module){
require_once "modules/' . $module;
$Module = new $module();
$Module ->getResults();
}
}
沿着这些思路有些东西是不正确的.基本上,扩展类创建一个由子类使用的类的实例。不知何故,这里有些地方不对劲,我猜这一切都与我没有使用singgleton的事实有关。我可以,如果我知道如何去卷曲的地方。
发布于 2014-11-14 21:33:32
多亏了热衣汗的Http客户端类(http://raynux.com/blog/2009/06/13/http-client-class-for-php-development/),我曾经愚蠢地认为我永远不可能只创建一个curl对象的实例。
基本上,我想要的是创建一个CURL SINGLETON类,这样我就不会反复创建相同对象的实例。
下面是我如何实现这一点的一个框架:
class Flowgear
{
static private $_instance;
//Rest properties here...
public function __cosntsruct()
{ $this->_token = $this->_username .':'. $this->_passoword; }
public function execute()
{
//Call a class that handles the actual API invocation passing all relevant data
}
static public function &getInstance()
{
if(self::$_instance == null){
self::$_instance = new self;
}
return self::$_instance;
}
}
然后,我简单地通过调用Flowgear::getInstance()来获取类的一个实例;
https://stackoverflow.com/questions/26862929
复制相似问题