Search code examples
phpyiiautoloadautoloaderspl-autoload-register

How to register Yii's autoloader in an external application?


I want to try Yii, but I don't want use it as my main framework. In other words, I want to use my own framework while also using some of Yii's features. I figured that in order to be able to instantiate Yii's classes from my application, I'd just need to register Yii's autoloader from my application, probably in a way similar to this:

spl_autoload_register
(
    function ($classname)
    {
        YiiBase::autoload($className);
    }
);

Of course, I'm gonna need to require or include the YiiBase class, so before I call the previous function, I do this:

$yiiBase = $_SERVER['DOCUMENT_ROOT'].'/yii/framework/YiiBase.php';
require_once($yiiBase);

But I get a "Cannot redeclare class YiiBase" error. What am I missing?


Solution

  • 1) Do not include YiiBase.php direcly, include yii.php. Because yii.php contains a class Yii which is used in all over framework code (even in YiiBase methods).

     $yii = $_SERVER['DOCUMENT_ROOT'].'/yii/framework/yii.php';
     require_once($yii);
    

    ( and YiiBase.php is included in yii.php by default)

    2) register your autoload handler in this way. (Yii has built-in functionality to add custom autoload handlers ).

    $my_autoload =  function($class) { ... };
    // OR
    // $my_autoload = array('MyClass', 'my_autoload')
    
    YiiBase::registerAutoloader($my_autoload, true);
    

    The second parameter true tells whether to append/prepend the new autoloader after/before the default Yii autoloader

    if the YiiBase.php included, then Yii's default autoloader will also gets included. No need to call YiiBase::autoload() explicitly in you code. Ref: check the last line in YiiBase.php file