我具有连接到外部端点的api特性。我想在称为ProductClass的类中使用此特征。该特征与该类位于同一文件夹中,但出现错误是我在该类中添加了使用ApiTrait的功能。错误表示无法找到特征,因此,如果我在类文件的顶部包含特征文件,则会出现此错误,无法在其中找到ApiTraitProductClass \ 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);
}
}
如果使用自动加载程序,则永远不需要此:
include_once("ApiTrait.php");
您已经在ApiTrait命名空间中定义了您的特征:
namespace ApiTrait;
trait ApiTrait { ... }
即,特征的完整路径为\ApiTrait\ApiTrait
。如果在定义的名称空间以外的其他名称空间中使用特性,则在引用它时需要在根名称空间中进行锚定,方法是在其前面加上反斜杠:
namespace ProductClass;
class Product implements DataInterface
{
use \ApiTrait\ApiTrait;
否则,如果您在没有前导反斜杠的情况下执行use ApiTrait\ApiTrait;
,则PHP认为您是指当前名称空间,即ProductClass
,产生\ProductClass\ApiTrait\ApiTrait
-该名称空间不存在,因此会出现错误。] >
而且,看起来您只是将每个类都放在自己的名称空间中。不要那样做使用名称空间将常见项目分组,例如,如下所示:
namespace Traits;
trait Api { ... }
namespace Traits;
trait Foo { ... }
namespace Traits;
trait Bar { ... }
namespace App;
class Product {
use \Traits\Api;
use \Traits\Foo;
use \Traits\Bar;
}