Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using classes without namespace with Yii2

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.

like image 643
alwaysLearn Avatar asked Jan 24 '15 17:01

alwaysLearn


1 Answers

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.

like image 94
arogachev Avatar answered Nov 01 '22 09:11

arogachev