Answer the question
In order to leave comments, you need to log in
How to work with dependencies in the controller?
There is an essence
class Company {
private $name;
public function __construct($name) {
$this->name = $name;
}
}
interface RepositoryInterface {
public function add(Company $company): void;
}
class MySqlRepository implements RepositoryInterface {
private $db;
public function __construct(DbConnection $db) {
$this->db = $db;
}
public function add(Company $company): void {
$name = $company->name;
$stmt = $this->db->prepare("INSERT INTO company (name) VALUES $name");
$stmt->execute();
}
}
class CompanyService {
private $repository;
public function __construct(RepositoryInterface $repository) {
$this->repository = $repository;
}
public function createCompany($dto): void {
$this->repository->add($dto);
}
}
class Controller {
private $service;
public function __construct(CompanyService $service) {
$this->service = $service;
}
public function actionCreate() {
//* получаем dto из формы
$dto;
$this->service->createCompany($dto);
}
}
$db = new DbConnection('127.0.0.1', 'root', 'dbname', '');
$repository = new MySqlRepository($db);
$service = new CompanyService($repository);
class Controller {
private $service;
/** Где это должно быть? */
$db = new DbConnection('127.0.0.1', 'root', 'dbname', '');
$repository = new MySqlRepository($db);
$service = new CompanyService($repository);
*///
public function __construct(CompanyService $service) {
$this->service = $service;
}
public function actionCreate() {
//* получаем dto из формы
$dto;
$this->service->createCompany($dto);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question