Yii Framework: setPathOfAlias() returns null

穿精又带淫゛_ 提交于 2019-12-25 04:24:15

问题


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!


回答1:


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',
    ),
    ...



回答2:


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 :)



来源:https://stackoverflow.com/questions/23850119/yii-framework-setpathofalias-returns-null

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