Using classes without namespace with Yii2
Asked Answered
R

2

11

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.

Rhynchocephalian answered 24/1, 2015 at 17:18 Comment(5)
And what is the error?Yim
@Yim class not found and when I try to include it manually it says cannot redeclare itRhynchocephalian
Make sure you have extension installed and it files exist in vendor folder.Yim
@Yim I have installed it using composer using ' "2Checkout/2checkout-php":"@stable"' under require sectionRhynchocephalian
Updated the answer, It should work now.Yim
Y
9

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.

Yim answered 24/1, 2015 at 17:57 Comment(1)
Please see the edit . I am unable to make it work :(Rhynchocephalian
M
0
/* Try this  */
public function actionTest(){
    //package
    require(Yii::getAlias('@vendor')."/Excel/Spreadsheet_Excel_Reader.php");

    $exldata = new \Spreadsheet_Excel_Reader();


}
Mylander answered 10/2, 2017 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.