我试图使用Php league container在AdminController中注入服务:
class App {
public function __construct() {
$container = new Container;
$container->add(CompanyCreateService::class)
->addArgument(CompanySqlRepository::class);
$container->add(CompanySqlRepository::class)
->addArgument(DbConnection::class)
->addArgument(Hydrator::class);
$container->add(DbConnection::class);
$container->add(Hydrator::class);
$container->add(AdminController::class)
->addArgument($container->get(CompanyCreateService::class));
$container->get(AdminController::class);
$this->actionIndex();
}
public function actionIndex() {
$controller = new AdminController();
}
}
使用CompanyCreateService作为注入的Admincontroller
class AdminController {
public $companyService;
public function __construct(CompanyServiceInterface $companyService) {
$this->companyService = $companyService;
$this->actionCreate();
}
public function actionCreate() {
$dto = ...
$this->companyService->createCompany($dto);
}
它将dto保存到数据库中,这是正常的,但是我遇到了错误
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Site\Company\Application\AdminController::__construct(), 0 passed and exactly 1 expected in ... AdminController.php
My classes:
class CompanySqlRepository implements CompanyRepositoryInterface {
private $hydrator;
private $db;
public function __construct(DbConnection $db, Hydrator $hydrator) {
$this->db = $db;
$this->hydrator = $hydrator;
}
class CompanyCreateService implements CompanyServiceInterface {
private $repository;
public function __construct(CompanyRepositoryInterface $repository) {
$this->repository = $repository;
}
public function createCompany($dto): void {
$this->repository->add($dto);
}
如何正确使用Di容器?为何即使出错也可以将其保存到数据库中?