PHP __call()
在对象中调用一个不可访问方法时,__call() 会被调用。
示例
废话不多说,直接上代码。
<?php
namespace App\ThirdPartyRequest;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
/**
* @method wxPayment(array $params)
* @method zfbPayment(array $params)
* @method couponPayment(array $params)
*/
class PayRequest
{
// 接口地址
protected $baseUri = "https://www.xxx.com";
// 请求客户端
protected $client = NULL;
// 可供访问的接口集合
protected $uriMap = [
'wxPayment' => '/v1/wx_payment',
'zfbPayment' => '/v1/zfb_payment',
'couponPayment' => '/v1/coupon_payment',
];
/**
* HTTP Client 发送请求
*
* @param string $uri
* @param array $params
*
* @return array
* @throws Exception|GuzzleException
*/
protected function send(string $uri, array $params): array
{
// 根据使用自己项目中的 HTTP Client,当前以 GuzzleHttp 为例,示例代码如下:
if (is_null($this->client)) {
$this->client = new Client(['base_uri' => $this->baseUri]);
}
$response = $this->client->request('POST', $uri, $params);
if ($response->getStatusCode() == 200) {
$result = $response->getBody()->getContents();
return json_decode($result, TRUE);
}
throw new Exception($response->getBody()->getContents());
}
/**
* 在对象中调用一个不可访问的方法时调用
*
* @param string $method
* @param array $arguments
*
* @return array
* @throws Exception|GuzzleException
*/
public function __call(string $method, array $arguments)
{
$methods = array_keys($this->uriMap);
if (!in_array($method, $methods)) {
throw new Exception('不支持的方法');
}
return $this->send($this->uriMap[$method], ...$arguments);
}
}
调用方式:
(new PayRequest())->wxPayment(['amount' => 1000]);
(new PayRequest())->zfbPayment(['amount' => 1000]);
(new PayRequest())->couponPayment(['amount' => 1000]);
这种写法有个好处,当再增加新接口调用的时候,只需简单配置下即可。
比如,需要新增加银行卡支付,只需要在 $uriMap 中增加:
'bankCardPayment' => '/v1/bank_card_payment',
最好再增加一行注释,这样便于编辑器代码提示,不增加也不影响代码运行。
* @method bankCardPayment(array $params)
THE END
匿名
2025-10-22
盖楼盖楼!
匿名
2025-08-11
沙发沙发
匿名
2025-08-10
https://at.oiik.cn/bing.html
匿名
2025-02-21
实用,我在开发https://minmail.app/时候使用到了
王飞翔
2024-12-30
亲爱的朋友:您好!中国疫情持续蔓延,很多人症状非常严重持久不愈,医院人满为患,各年龄段随地倒猝死的现象暴增,多省感染手足口、甲流、乙流、支原体、合胞及腺病毒的儿童不断攀升,目前各种天灾人祸,天气异象频发。古今中外的很多预言都说了这几年人类有大灾难,如刘伯温在预言中说 “贫者一万留一千,富者一万留二三”,“贫富若不回心转,看看死期到眼前”, 预言中也告诉世人如何逃离劫难的方法,真心希望您能躲过末劫中的劫难,有个美好的未来,请您务必打开下方网址认真了解,内有躲避瘟疫保平安的方法。网址1:https://github.com/1992513/www/blob/master/README.md?abhgc#1 网址2:bitly.net/55bbbb 网址3:https://d3ankibxiji86m.cloudfront.net/30gj 如打不开请多换几个浏览器试
匿名
2024-12-12
Backdata 搜索引擎网址提交入口:https://backdata.net/submit-site.html