I have Basic Project Template of Yii 2 installed and I'm trying to test autoloading of classes.
So I added a Test/Test.php file in root folder of the project:
<?php
namespace app\Test;
class Test
{
public static function sayHello()
{
echo 'Hello, world!';
}
}
And I have a test-autoload.php script which is calling the Test class:
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
app\Test\Test::sayHello();
But when I open test-autoload.php in browser, I get an error:
Fatal error: Uncaught Error: Class "app\Test\Test" not found in C:\Web\OpenServer\domains\taskforce\web\test-autoload.php:6 Stack trace: #0 {main} thrown in C:\Web\OpenServer\domains\taskforce\web\test-autoload.php on line 6
But there shouldn't be one, because according to documentation:
When using the Basic Project Template, you may put your classes under the top-level namespace app so that they can be autoloaded by Yii without the need of defining a new alias. This is because @app is a predefined alias, and a class name like app\components\MyClass can be resolved into the class file AppBasePath/components/MyClass.php, according to the algorithm just described.
If I add my class in classMap, everything starts to work, but I don't want to do that and that's why I'm using top-level namespace "app".
What am I doing wrong?
The app
namespace is handled by Yii's autoloader. As you've quoted from documentation it uses aliases to resolve corresponding namespaces. The problem is that aliases are initialized during application bootstrap. If the application is not bootstraped as in your case, the @app
alias is not defined and the autoloader cannot load classes from app
namespace.
If you need to use app
namespace outside of bootstrapped application you can define it in composer.json autoload section instead.