yii 3.0 必须通过 psr-11 容器显式注册并注入依赖,入口改用 applicationfactory 创建应用实例,配置需返回 configurator 或闭包数组,控制器仅支持构造函数类型提示注入,组件注册改用 $container->set()。

要在 Yii 3.0 中让控制器、服务或中间件真正拿到可用的依赖实例,必须绕过 Yii::$app 这条老路,用 PSR-11 容器显式注册并注入——否则调用 $this->db 或 new UserService() 会直接报错或返回 null。
入口文件重写:从 Yii::$app 到 ApplicationFactory
打开 public/index.php,删掉所有 Yii::createObject() 和 Yii::$app 的引用。替换为 yiisoft/yii-web 提供的 ApplicationFactory:
require __DIR__ . '/../vendor/autoload.php';
use Yiisoft\Yii\Web\ApplicationFactory;
$factory = new ApplicationFactory();
$app = $factory->create($config);
$app->run();
这一步不可跳过——Yii 3.0 入口不再启动全局单例,而是通过工厂构造一个 Application 实例,后续所有依赖都从此处容器中解析。
配置容器:用 Configurator 或原生数组+闭包
config/web.php 不再返回简单数组,必须返回 Configurator 实例或 PHP 8.1+ 原生数组 + 闭包组合:
方法一:使用 Configurator(推荐)
return (new \Yiisoft\Config\Configurator())
->withDefinitions([\n Psr\Log\LoggerInterface::class => [\n 'class' => \Yiisoft\Log\Target\FileLogger::class,\n 'file' => '@runtime/logs/app.log',\n ],\n App\Service\UserService::class => [\n 'class' => App\Service\UserService::class,\n '__construct()' => [\n 'logger' => Psr\Log\LoggerInterface::class,\n ],\n ],\n ]);
方法二:纯数组+闭包(PHP 8.1+ 支持)
return [
Psr\Log\LoggerInterface::class => fn () => new \Yiisoft\Log\Target\FileLogger('@runtime/logs/app.log'),
App\Service\UserService::class => fn (Psr\Log\LoggerInterface $logger) => new App\Service\UserService($logger),
];
【闭包参数名必须与接口类名完全一致】,否则容器无法自动解析——比如写成 function($log) 就会失败,必须是 $logger 且类型声明为 Psr\Log\LoggerInterface。
控制器中获取依赖:只允许构造函数注入
第一步:删除控制器里所有 Yii::$app->get('xxx')、Yii::getContainer()->get(...) 等调用;
第二步:在控制器构造函数中声明所需依赖,类型提示必须精确到接口或具体类:
public function __construct(
private UserServiceInterface $userService,
private LoggerInterface $logger
) {}
第三步:在 action 方法中直接使用 $this->userService->find($id),无需任何 get() 或 createObject() 调用。
这一步若漏掉类型提示,或用了非接口类名(如写 UserService 而非 UserServiceInterface),容器将无法匹配定义,抛出 UnresolvableDependencyException。
组件注册:不再有 'components' 键,改用容器 set()
在 config/common.php 或 config/web.php 的 definitions 数组中,把原来 Yii 2.x 的 'components' => ['db' => [...]] 彻底移除。
改用容器级注册方式:
$container->set(\Psr\Cache\CacheInterface::class, \Yiisoft\Cache\SimpleCache::class);
$container->set(\Yiisoft\Db\Connection\ConnectionInterface::class, fn () => new \Yiisoft\Db\Mysql\Connection(...));
注意:set() 第一个参数必须是接口或抽象类,第二个参数可以是类名、实例或闭包。如果传字符串类名,容器会在需要时自动 new 实例;如果传闭包,每次解析都会执行一次。











