我具有连接到外部端点的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);
}
}
答案 0 :(得分:2)
如果您使用的是自动加载程序,则永远不需要它:
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 ProductClass;
use ApiTrait\ApiTrait;
class Product implements DataInterface
{
use 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;
}