Use the DI Container and ContainerProxy
masterNano provides access to a Dependency Injection (DI) container. You can manually set instances using $app->getContainer()->set().
Important Convention: In all closures managed by Nano (routes, middleware, exception handlers, etc.), $this is automatically bound to an instance of Hyperf\Nano\ContainerProxy. You can use $this->get(ClassName::class) to retrieve services from the container.
<?php
use Hyperf\Nano\ContainerProxy;
use Hyperf\Nano\Factory\AppFactory;
class Foo {
public function bar() { return 'bar'; }
}
$app = AppFactory::create();
$app->getContainer()->set(Foo::class, new Foo());
$app->get('/', function () {
/** @var ContainerProxy $this */
$foo = $this->get(Foo::class);
return $foo->bar();
});
$app->run();