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?
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.