Using classes without namespace with Yii2

倾然丶 夕夏残阳落幕 提交于 2019-11-30 08:57:42

问题


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?

EDIT

As suggested I tried to use class as

$sale = new \Twocheckout_Sale();

but still I am unable to make it work.


回答1:


When the class does not have namespace it means it's in the root namespace.

Option 1:

use Twocheckout;

...

Twocheckout::format('json');

Option 2:

\Twocheckout::format('json');

For example, PHPExcel extension also doesn't have namespaces, similar question was answered on official forum.

Related questions:

Importing class without namespace to namespaced class

How to use "root" namespace of php?

Official PHP documentation:

http://php.net/manual/en/language.namespaces.fallback.php

Update:

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();

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.




回答2:


/* Try this  */
public function actionTest(){
    //package
    require(Yii::getAlias('@vendor')."/Excel/Spreadsheet_Excel_Reader.php");

    $exldata = new \Spreadsheet_Excel_Reader();


}


来源:https://stackoverflow.com/questions/28128117/using-classes-without-namespace-with-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!