【发布时间】:2019-11-05 15:41:38
【问题描述】:
我有一个连接到外部端点的 api 特征。我想在一个名为 ProductClass 的类中使用这个特性。该特征与该类位于同一文件夹中,但出现错误是我在类中添加了 use ApiTrait 。错误说它找不到特征,所以如果我在类文件的顶部包含特征文件,我会收到这个错误,找不到 ApiTrait 产品类\ApiTrait。 如果我将特征传递给构造函数,当我调用 ProductClass 时,我的索引页面会出现错误,因为我没有传递特征。我不想将任何参数传递给构造函数,只是将字符串顶部附加到 .env 端点。任何线索都非常感谢 这是我的 ApiTrait 代码
<?php
namespace ApiTrait;
require './vendor/autoload.php';
use GuzzleHttp\Client;
trait ApiTrait
{
protected $url;
protected $client;
public function __construct()
{
$this->url = getenv('API_URL');
$this->client = new Client();
}
private function getResponse(String $uri = null)
{
$full_path = $this->url;
$full_path .=$uri;
try {
$response = $this->client->get($full_path);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
}
return json_decode($response->getBody()->getContents(), true);
}
public function getAPIData($uri)
{
return $this->getResponse($uri);
}
}
这是我的 ProductClass 代码
<?php
namespace ProductClass;
include_once("ApiTrait.php");
use DataInterface\DataInterface;
class Product implements DataInterface
{
use ApiTrait\ApiTrait
private $api;
public function __construct(ApiTrait\ApiTrait $apiTrait) {
$this->api = $apiTrait;
}
private function getResponse($append, $try) {
$urlAppend = $append;
$good_data = false;
do{
try{
$result = $this->api->getAPIData($urlAppend);
//check data to see if valid
if(!array_key_exists( "error",$result)){
$good_data = true;
return $result;
}
}
catch(Exception $e){
//call api upto 10 times
if($try < 10) {
sleep(1);
getData($append, $try++);
} else { //return a connection error
$api_error['error']='unable to connect to api';
return $api_error;
}
}
} while($good_data === false);
}
public function getData($append, $try = 0)
{
return $this->getResponse($append, $try);
}
}
【问题讨论】:
-
你不能在构造函数中传递特征,这只是语法错误