gpt4 book ai didi

php设计问题

转载 作者:行者123 更新时间:2023-12-04 06:43:45 25 4
gpt4 key购买 nike

我有以下类(class):

class Apiconnect {

const URL = 'https://someurl.com/api.php';
const USERNAME = 'user';
const PASSWORD = 'pass';

/**
*
* @param <array> $postFields
* @return SimpleXMLElement
* @desc this connects but also sends and retrieves the information returned in XML
*/

public function Apiconnect($postFields)
{
$postFields["username"] = self::USERNAME;
$postFields["password"] = md5(self::PASSWORD);
$postFields["responsetype"] = 'xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($data);
if($xml->result == "success")
{
return $xml;
}
else
{
return $xml->message;
}
}
}

现在我想在将使用它的其他类的其他方法上使用这个连接类。

所以,我正在考虑做一个类(不确定抽象在这里是否合适),如下所示:
abstract class ApiSomething
{
protected $_connection;
protected $_postFields = array();

/**
* @desc - Composition.
*/

public function __construct()
{
require_once("apiconnect.php");
$this->_connection = new Apiconnect($this->_postFields);
}

public function getStuff()
{

//this is the necessary field that needs to be send.
//Containing the action that the API should perform.
$this->_postFields["action"] = "dosomething";
...
}

}

我需要在 getStuff() 方法上使用 $_connection 属性,以便将“操作”发送到 API 中。然而,不确定如何实现。

请问有什么帮助吗?

最佳答案

为什么不扩展你的对象而不是包含一些东西。 APIConnect 应该是抽象类,API 应该扩展它。

abstract class ApiConnect {
protected $_something;
protected $_something2;
protected $_curlResource;
function __construct($param1){
/* do curl setup here and save it to $this->_curlResource */
}
}

class ApiSomething extends ApiConnect {
protected $_paramForBase;
function __construct(){
super($this->_paramForBase);
echo "Var from base: ".parent::_something;
/* do more things with curl here, through parent::_curlResource */
}

function setParamsForCurlCall(){
/* add curl parameters with curl here, through parent::_curlResource */
}

function execCurl(){
/* do your final curl call here */
}
}

然后你可以用你的抽象类做任何你想做的事情,你可以用 API 来拥有基类的所有控制逻辑。当然,如果您要在多个类中扩展 ApiConnect,您只想这样做。

关于php设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com