我具有连接到外部端点的api特征。我想在称为ProductClass的类中使用此特征。该特征与该类位于同一文件夹中,但出现错误是我在该类中添加了使用ApiTrait的功能。错误表示找不到特质,因此,如果我在类文件的顶部包含特质文件,则会出现此错误,无法在其中找到ApiTrait ProductClass \ 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);
}
}