在Yii2中使用不带名称空间的类 [英] Using classes without namespace with Yii2

查看:333
本文介绍了在Yii2中使用不带名称空间的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Checkout SDK 与Yii2一起使用,但是由于该库不支持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?

编辑

根据建议,我尝试将class用作

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没有.通过要求一个主要的抽象类来包括所有类.甚至在官方自述文件中提到:

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中要求它:

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中使用不带名称空间的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆