Yii Framework: setPathOfAlias() returns null

2019-09-01 10:01发布

I am trying to put MaxMind's GeoIp2 into my Yii application. Basically, I copied the files under "src" (see previous link) under protected -> vendors -> maxmind. The folder structure under my application is the following:

protected
|---- vendors
      |---- Zend
      |---- maxmind
           |---- Database
                 |---- Reader.php
           |---- Model
           |---- ...
      |---- ...

After that, I created the path aliases into my index.php file:

Yii::setPathOfAlias('Zend', Yii::getPathOfAlias('application.vendors.Zend'));
Yii::setPathOfAlias('GeoIp2',   Yii::getPathOfAlias('application.vendors.maxmind'));

The path works just fine for the 'Zend' alias, but it fails for 'GeoIp2' by returning null.

Yii::createApplication("FrontendApplication", $config)->run();
echo "Path 1: " . Yii::getPathOfAlias("Zend"). '<br />'; // Correct path!
echo "Path 2: " . Yii::getPathOfAlias("GeoIp2"). '<br />'; // <==== NULL
echo "Maxmind path: " . Yii::getPathOfAlias('application.vendors.maxmind'). '<br />'; // correct path

var_dump(is_dir(Yii::getPathOfAlias('application.vendors.maxmind'))); // true

Any ideas why this could happen?

Thanks!

2条回答
三岁会撩人
2楼-- · 2019-09-01 10:14

getPathOfAlias() call to create path aliases are created in the constructor of CApplication. But the constructor wasn't called yet at the point when main.php is included.

To configure path aliases use the aliases property in your main.php. Like this:

return array(
    'aliases' => array(
        'GeoIp2' => 'application.vendors.maxmind',
    ),
    ...
查看更多
你好瞎i
3楼-- · 2019-09-01 10:15

Fixed! The solution:

Instead of calling setPathOfAlias() into the index.php file I added the aliases into my configuration file (i.e. protected -> config -> main.php), as paramaters, like this:

$config = array(
    'import' => array(),
     'components' => array(),
     ...
     'aliases' => array(
          'Zend' => 'application.vendors.Zend',
          'Maxmind' => 'application.vendors.Maxmind',
        ),
      ...
      'params' => array()
    );

Apparently, index.php is not the right place to declare this. It may be because of the autoloader, I am not 100% sure, but since Zend has an autoloader and MaxMind doesn't, that's why it may work for Zend and not for MaxMind. Doing this made the things work. As you may notice, I also moved the Zend alias path to the same place, for consistency reasons :)

查看更多
登录 后发表回答