简体   繁体   中英

How to Instatiate a class with same name while autoloading a 3rd party Library with Yii Framework?

Importing vendor folder In config/main.php :

'import'=>array(
    'application.vendor.*'
),

Add an alias (Don't know if required):

Yii::setPathOfAlias('oauth', '/../vendor/bshaffer/oauth2-server-php/src/OAuth2');

So according to the Oauth documentation I use:

$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

so I change it to:

$storage = new Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

But it is picking up the wrong class here. How can I make sure it is using the one from the 3rd-party library.

Remove the import configuration, as that won't be sufficient since Yii's autoloader doesn't work recursively. Instead, you need to take advantage of the fact that Yii supports PSR-0 autoloading, (and that this package uses PSR-0), if you set the alias path correctly.

Add the following to your main config:

Yii::setPathOfAlias(
    'OAuth2', 
    __DIR__.'/../vendor/bshaffer/oauth2-server-php/src/OAuth2'
);

You MUST use the alias OAuth2 , and not oauth or any other variation.

In a file that you wish to use the class, place:

use OAuth2\Storage\Pdo;

at the top of the file. At that point, you can reference the Pdo object as you did at the end of your question:

$storage = new Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

Note: the use statement is unnecessary if you simply directly reference the class via it's namespace, as you did in the 2nd to last code block in your question:

$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM