如何包含REST API与spl_autolload ?



我试图创建一个自动加载器,但在我的类(命名:发票))我需要添加一个框架(REST API命名为APIclient),在代码中有更多的require语句,我得到"Warning: include_once(): Failed opening for inclusion"错误。

首先,我在/App/Orders/中创建了一个类,文件名为Invoice.php

<?php
namespace APPOrders;
use APPConfig;
use APPOrdersDataValidator;
use APPOrdersProducts;
use APPDataBase;
use APPLogErrors;
class Invoice {
private $config;
private $PDO;

public function __construct(){
$this->config = new Config;
$this->PDO = (new DataBase)->DB_CONN();
$apiSF = new APIclient("XYZ", "XYZ"); //This is the REST API I WANT TO INCLUDE
}
}
?>

所有的类(对象)加载良好,除了Rest API类(APIclient)

下面是我在requests/index.php文件中的自动加载器:

<?php
spl_autoload_register(function($path){
include_once dirname(__DIR__, 2) . "/" . str_replace("\", '/', $path) . '.php';
});
?>

Rest API文件(apicclient .php))我想在代码中包含更多的require语句:

if (!class_exists('Requests')) {
require_once('Requests.php');
}

这就是为什么我的自动装填机不工作。

所以简而言之,我想包含一个REST API与自动加载器,其中是另一个请求语句。

我试图在Invoice.php文件中要求REST API文件,但也没有运气。REST API文件的位置为:

"APP/API/APIclient/APIclient.php"

以及我如何尝试包含:

new APPAPIAPIclientAPIclient("XYZ", "XYZ"); //This is the REST API I WANT TO INCLUDE

自动加载器找到了apicclient .php文件,并包含了apicclient .php中需要的内容,但无法打开Requests.php文件。

我该如何解决这个问题?谢谢你!

编辑:

文件夹结构如下:

ROOT:
│   
├───APP
│   ├───API
│   │   └───APIclient
│   │           APIclient.php
│   │           Requests.php
│   │           
│   └───Orders
│           Invoice.php
│           
└───requests
└───Orders
createInvoice.php

我在没有类方法的情况下重新创建了错误,只是为了使代码更具可读性。

所以文件的内容:

APIclient.php:

if (!class_exists('Requests')) {
require_once('Requests.php');
}
class APIclient {

protected
$email,
$apikey;

public function __construct($email, $apikey)
{
//Requests::register_autoloader();
$this->email      = $email;
$this->apikey     = $apikey;
}

}

Requests.php

class Requests {

}

Invoice.php

namespace APPOrders;
class Invoice {

public function __construct(){
$apiSF = new APPAPIAPIclientAPIclient("XYZ", "XYZ"); 
}

public function someFunction(){
return "hello there";
}

}

createInvoice.php

spl_autoload_register(function($path){
include_once dirname(__DIR__, 2) . "/" . str_replace("\", '/', $path) . '.php';
});

use APPOrdersInvoice;
echo $invoice = (new Invoice())->someFunction();

在API文件夹(哪里去所有的API文件),我只是不想改变代码和命名空间为REST API,如果可能的话。

也许我找到了这个问题的答案(但我不确定这是最好的方法)

在spl_autolload中我添加了if is_file语句

spl_autoload_register(function($path){
$file_path = dirname(__DIR__, 2) . "/" . str_replace("\", '/', $path) . '.php';
if(is_file($file_path)){
include_once $file_path;
}
});

在Invoice.php文件中,我使用require语句要求API文件:

require dirname(__DIR__, 1) . "/API/APIclient/APIclient.php";

通过这种方式,我可以在构造函数中使用对象:

public function __construct(){
$this->apiSF = new APIclient("XYZ", "XYZ"); 
}

但是,如果我打印出spl_autolload请求的文件$file_path变量,在我的例子中,有很多文件不存在(因为API)。

最新更新