编程语言
首页 > 编程语言> > php – 在Symfony2项目上使用外部非PSR-0库的正确方法

php – 在Symfony2项目上使用外部非PSR-0库的正确方法

作者:互联网

我正在开发一个应用程序,它将通过他们的REST PHP SDK连接到Intuit Quickbooks API.在基本的PHP中,我的工作没有问题,因为我加载文件如下:

require_once('../api/config.php');  // Default V3 PHP SDK (v2.0.1) from IPP
require_once(PATH_SDK_ROOT . 'Core/ServiceContext.php');
require_once(PATH_SDK_ROOT . 'DataService/DataService.php');
require_once(PATH_SDK_ROOT . 'PlatformService/PlatformService.php');
require_once(PATH_SDK_ROOT . 'Utility/Configuration/ConfigurationManager.php');

现在我需要在Bundle中使用Symfony2控制器中的库,这是我怀疑的地方,我如何轻松实现这一目标?我阅读了很多文档link1,Symfony Class Loader Component和其他一些文档,但我甚至都不清楚.现在我已经在我的/ vendor文件夹中创建了这个结构,如图所示:

你的config.php文件可以看到有这样的代码:

/**
 * This file allows custom configuration of paths for XSD2PHP dependencies and
 * POPO classes.  Rarely necessary, but possible.
 *
 * @author Intuit Partner Platform Team
 * @version 1.0
 */

// Determine parent path for SDK
$sdkDir = __DIR__ . DIRECTORY_SEPARATOR;

if (!defined('PATH_SDK_ROOT'))
    define('PATH_SDK_ROOT', $sdkDir);

// Specify POPO class path; typically a direct child of the SDK path
if (!defined('POPO_CLASS_PATH'))
    define('POPO_CLASS_PATH', $sdkDir . 'Data');

// Include XSD2PHP dependencies for marshalling and unmarshalling
use com\mikebevz\xsd2php;
require_once(PATH_SDK_ROOT . 'Dependencies/XSD2PHP/src/com/mikebevz/xsd2php/Php2Xml.php');
require_once(PATH_SDK_ROOT . 'Dependencies/XSD2PHP/src/com/mikebevz/xsd2php/Bind.php');

// Includes all POPO classes; these are the source, dest, or both of the marshalling
set_include_path(get_include_path() . PATH_SEPARATOR . POPO_CLASS_PATH);
foreach (glob(POPO_CLASS_PATH.'/*.php') as $filename)
    require_once($filename);

// Specify the prefix pre-pended to POPO class names.  If you modify this value, you
// also need to rebuild the POPO classes, with the same prefix
if (!defined('PHP_CLASS_PREFIX'))
    define('PHP_CLASS_PREFIX',    'IPP');

并且有类加载魔法的地方,至少对于QBO PHP SDK方式,所以:

>我如何处理这个以便将类用作Symfony2我的意思是创建对象等等?
>既然这是非PSR-0库,会不会是Symfony Class Loader Component的解决方案?
>你能给我一些想法甚至一些代码来帮我搞定这个吗?

解决方法:

Symfony使用Composer.因此,包含SDK的最简单方法是大致使其与Composer兼容,无论如何.

这将需要包的根目录上的composer.json.创造它.

最简单的解决方案

在composer.json的自动加载部分中放置一个classmap指令:

"autoload": {
    "classmap": ['src/'],
},

然后,Composer将在生成自动加载文件时以递归方式扫描src /目录.因此,每个类都将在需要时导入,而无需更改名称空间或任何内容.

缺点是图书馆仍然没有遵循PSR0,包括所有风险.

费力的解决方案

PSR0-ify库通过编辑每个源文件来添加正确的命名空间并在每个文件的顶部使用指令.考虑到SDK中的类数,这很简单,但很费力.

然后,您可以添加包的composer.json的自动加载部分,如下所示:

"autoload": {
    "psr-0": {
        "QBO\\": "src/"
    }
},

替代方案

在搜索这个API时,我在packagist上发现了consolibyte/quickbooks-php这个…也许值得一试.

标签:php,symfony,autoload,autoloader,symfony2-4
来源: https://codeday.me/bug/20190624/1278592.html