1

I make a custom component(getter).

My custon component works well, because I test from a controler:

namespace app\controllers;

use Yii;

(...)

class SiteController extends Controller
{
    (...)

    public function actionTest()
    {   
         //OK, print numItems
         echo '<br>-Items: '.Yii::$app->getter->numItems;
    }       
}

Now I want to use my component from standard php file. This php file is inside the Yii project structure in cmd dir.

namespace app\cmd;

use Yii;

echo "Import ok<br>";

echo '<br>-Items: '.Yii::$app->getter->numItems;

echo "Script end";

The result of run script is "Import ok" and Fatal error: Class 'Yii' not found.

Why do I get a 'Class not found' error?

robsch
  • 9,358
  • 9
  • 63
  • 104
user3782779
  • 1,669
  • 3
  • 22
  • 36

1 Answers1

3

You have to do more than just say use Yii;.

Look into web/index.php for example:

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();

There you see that composer's autoload.php file gets required. And then the Yii.php. If you would do the same in your file the Yii class would be already found.

However, this is still not enough. In order to access Yii::$app you have to create an Application object that needs a configuration. This is what the last line in web/index.php does. This takes the whole configuration files into account. After that Yii::$app is accessible.

So what you want to achieve should be done in another way. Have a look into the documentation about Yii commands.

robsch
  • 9,358
  • 9
  • 63
  • 104
  • Is like "(new yii\web\Application($config))->run();" is a blocking function. Code after this call don't run. – user3782779 Mar 03 '15 at 14:30
  • No, I don't think it blocks. But don't try it that way! What do you want to achieve? – robsch Mar 03 '15 at 14:41
  • I need a url like: "mydomain/file.php" that receive POST request and call my custom component to process. – user3782779 Mar 03 '15 at 15:20
  • You can have a normal controller and action to get post parameters (Yii::$app->request->post()) and do the processing there. In this action you can return what ever you want, but you can also render a regular view which will be returned. Even better would be to redirect within the called action to another action so posted data won't get called twice, accidently. Put the feedback for the user in this second action ('Import successful!'). But you need to make the action callable with method 'post', otherwise you an MethodNotAllowHttpException. – robsch Mar 03 '15 at 15:34