问题描述
我想在 Yii2 中使用 Checkout SDK 但因为这个库不支持 PSR-4标准(命名空间)我很难集成它.我怎样才能将这个库用于我的目的?
I want to use Checkout SDK with Yii2 but since this library does not support PSR-4 standards (namespaces) I am having trouble to integrate it. How can I use this library for my purpose?
编辑
建议我尝试使用类作为
As suggested I tried to use class as
$sale = new Twocheckout_Sale();
但我仍然无法让它工作.
but still I am unable to make it work.
推荐答案
当类没有命名空间时,意味着它在根命名空间中.
When the class does not have namespace it means it's in the root namespace.
选项 1:
use Twocheckout;
...
Twocheckout::format('json');
选项 2:
Twocheckout::format('json');
例如,PHPExcel 扩展也没有命名空间,类似的问题在 官方论坛.
For example, PHPExcel extension also doesn't have namespaces, similar question was answered on official forum.
相关问题:
将没有命名空间的类导入到命名空间的类
如何使用root"php的命名空间?
官方 PHP 文档:
http://php.net/manual/en/language.namespaces.fallback.php
更新:
但是 PHPExcel
有自己的自动加载器,而 2Checkout
没有.通过要求一个主要的抽象类来包含所有类.它甚至在官方 readme 中提到:
But PHPExcel
has own autoloader, while 2Checkout
does not. All classes are included by requiring one main abstract class. It's even mentioned in official readme:
require_once("/path/to/2checkout-php/lib/Twocheckout.php");
所以你需要在使用库类之前手动包含它.可以借助别名来避免写全路径.
So you need to manually include it before using library classes. It can be done with help of alias to avoid writing full path.
use Yii;
...
$path = Yii::getAlias("@vendor/2checkout/2checkout-php/lib/Twocheckout.php");
require_once($path);
$sale = new Twocheckout_Sale();
在一个地方使用是可以的,但是如果要在很多地方使用,最好在入口脚本index.php
中require它:
For usage in one place it's OK, but if it will be used in many places of application, it's better to require it in entry script index.php
:
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/2checkout/2checkout-php/lib/Twocheckout.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
我还建议阅读官方文档中关于 使用下载的库,根据特定的库,您可以使用更多选项.
I also recommend to read tips in official documentatiton about using downloaded libraries, there are more options you can use depending on the specific library.
这篇关于在 Yii2 中使用没有命名空间的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!