Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

You can take a look at some approaches of people integrating Yii with wordpress, you may not need to do ->run() the application, unless you need the controllers/routing, it also depends on what parts of the framework you pretend to use.

To do it for Yii2, this article explains it under the heading "Using Yii in Third-Party Systems" in the middle of the page.

Here is the relevant part to include on startup of your external application:

  require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
  $yiiConfig = require(__DIR__ . '/../config/yii/web.php');
  new yii\web\Application($yiiConfig); // Do NOT call run() here

Obviously, __DIR__ . '/../ may need to be adjusted to fit your directory layout.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top