DI 容器

  1. <?php
  2. use Hyperf\Nano\ContainerProxy;
  3. use Hyperf\Nano\Factory\AppFactory;
  4. require_once __DIR__ . '/vendor/autoload.php';
  5. class Foo {
  6. public function bar() {
  7. return 'bar';
  8. }
  9. }
  10. $app = AppFactory::create();
  11. $app->getContainer()->set(Foo::class, new Foo());
  12. $app->get('/', function () {
  13. /** @var ContainerProxy $this */
  14. $foo = $this->get(Foo::class);
  15. return $foo->bar();
  16. });
  17. $app->run();

所有 $app 管理的闭包回调中,$this 都被绑定到了 Hyperf\Nano\ContainerProxy 上。