如何仅在 Fat Free Framework (f3) 中需要时才在控制器中加载或 include/require 第三方库 php 文件

How to load or include/require 3rd party library php files in a controller only when needed in Fat Free Framework (f3)

我正在尝试在控制器中包含 ExactTarget api 的文件。基本上,ajax 请求将表单提交到路由 /send。在该路由的控制器中,我有一个 class,但是当它调用 ExactTarget 库时它失败了。

class sendexacttarget{
  public function send($f3)
  {
    $client = new ExactTargetSoapClient($wsdl, array('trace'=>1));
  }
}

我不想在 index.php 中加载 ExactTarget 文件,因为它会在每次请求时加载。理想情况下,我只想在发送函数中将其加载到此处。我试过 require() 和 include() 但都不起作用。

我正在尝试包含一个文件 exacttarget.php,该文件有一个调用 soap-wsse.php 的 require 语句,它有另一个调用 xmlseclibs.php.

的 require 语句

所以第一个问题:是否可以从控制器加载这些文件,如果可以,如何加载?

问题的第二部分是这样的。我能够将这三个文件中的所有 PHP 合并到一个文件中,并从 index.php 中包含,但我没有成功地将它们称为单独的文件。我试过这个:

$f3->set('AUTOLOAD','App/Controllers/;vendor/exacttarget/xmlseclibs.php;vendor/exacttarget/soap-wsse.php;vendor/exacttarget/exacttarget.php');

但是没用。

我也在另一个 SO 线程中尝试过这个:

$f3->set('AUTOLOAD','App/Controllers/;vendor/exacttarget/');
$params = require 'vendor/exacttarget/exacttarget.php';

无效。我认为最后一段代码工作了一点,但后来就停止工作了。我想知道是否有一些缓存正在进行?

无论如何,如果有人可以帮助我包含这个库,即使是在所有页面上,我也会非常感激。此外,我正在使用的这个库无法通过 composer 获得,所以我认为使用 composers autoload 不是一个选项。

谢谢。

AUTOLOAD 自动加载器不支持文件名。看起来你正在使用 Composer 所以请使用它的自动加载器:

require_once 'vendor/autoload.php'

请调整 vendor 相对于需要 autoload.php 文件的文件的路径(或使用绝对路径)。

框架自动加载器需要满足以下条件才能正常工作:

  • 每个文件一个 class
  • 每个文件的名称都与它包含的 class 相似,并且位于代表其命名空间的目录结构中

有关详细信息,请参阅 documentation and this SO question

由于您尝试加载的外部库不符合这些要求,我建议您采用三种解决方案:

1) 需要控制器中的所有依赖项:

  public function send($f3) {
    require('vendor/exacttarget/xmlseclibs.php');
    require('vendor/exacttarget/soap-wsse.php.php');
    require('vendor/exacttarget/exacttarget.php');
    $client = new ExactTargetSoapClient($wsdl, array('trace'=>1));
  }

2) 创建一个需要所有依赖项和 return ExactTargetSoapClient 实例的服务:

// index.php
f3->SOAP = function($wsdl,array $options=[]) {
    require_once('vendor/exacttarget/xmlseclibs.php');
    require_once('vendor/exacttarget/soap-wsse.php.php');
    require_once('vendor/exacttarget/exacttarget.php');
    return new ExactTargetSoapClient($wsdl,$options+['trace'=>1]);
}

// controller
public function send($f3) {
  $client = $f3->SOAP($wsdl);
}

注意:如果 $wsdl 和 $options 参数与所有其他应用程序相同,您甚至可以删除函数参数并使用简单的 $f3->SOAP()

3) 将三个文件连接成一个正确命名的文件并自动加载:

// vendor/exacttargetsoapclient.php
<?php
class ExactTargetSoapClient extends SoapClient {

// etc.

class WSSESoap {

// etc.

/**
* xmlseclibs.php
* etc.

现在设置自动加载器:

// index.php
$f3->AUTOLOAD = 'App/Controllers/;vendor/';

大功告成:

// controller
  public function send($f3) {
  $client = new ExactTargetSoapClient($wsdl, array('trace'=>1));
}