我收到了关于我的代码的反馈,说我错误地使用了依赖注入:
您正在使用 DI,但除了
Request
和之外,您没有在任何地方使用它Response
。以下 10 行将始终实例化对象,即使您从未使用它们。
在这些线上我有类似的东西
$router->map('GET', '/tokens/{id}', [new APIController($server, $tokenRepository, $logger), 'get']);
$router->map('GET', '/tokens', [new APIController($server, $tokenRepository, $logger), 'list']);
....
$response = $router->dispatch($container->get('request'));
根据文档,这似乎是正确的方法。引导程序.php:
$container = new Container;
$logger = new Logger('book');
$tokenRepository = new RedisTokenRepository($predis, $logger);
$container->add(Logger::class);
$container->add(Server::class);
$container->add(TokenController::class)->addArguments([Server::class, $logger]);
$container->add(APIController::class)->addArguments([Server::class, $tokenRepository, $logger]);
$strategy = (new ApplicationStrategy)->setContainer($container);
$router = (new Router)->setStrategy($strategy);
$router->map('GET', '/', [new Acme\APIController, 'someMethod']);
控制器
class APIController
{
private $server;
private $tokenRepository;
private $logger;
public function __construct(
Server $server,
TokenRepositoryInterface $tokenRepository,
LoggerInterface $logger
)
{
$this->server = $server;
$this->tokenRepository = $tokenRepository;
$this->logger = $logger;
}
谁能解释我做错了什么?