S
S
slip312019-07-22 15:06:12
PHP
slip31, 2019-07-22 15:06:12

How to work with dependencies in the controller?

There is an essence

class Company {

    private $name;

    public function __construct($name) {
        
        $this->name = $name;
    }
}

i want to keep it
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();
    }
}

using the service
class CompanyService {

   private $repository;

    public function __construct(RepositoryInterface $repository) {         
                $this->repository = $repository;
    }
    public function createCompany($dto): void {
        $this->repository->add($dto);
    }
}

Well, the controller
class Controller {
    private $service;

    public function __construct(CompanyService $service) {         
        
                $this->service = $service;
    }
    
    public function actionCreate() {
        //* получаем dto из формы
        $dto;
        $this->service->createCompany($dto);
    }
}

Correctly I understand that I have to forward everywhere:
$db = new DbConnection('127.0.0.1', 'root', 'dbname', '');
$repository = new MySqlRepository($db);
$service = new CompanyService($repository);

And how can I pass this to the controller I'm working with? After all, the service has a repository in the constructor, does the repository have a connection to the database in the constructor? Should this be created in the controller's constructor somehow?
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);
    }
}

How is this done according to OOP?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OnYourLips, 2019-07-22
@OnYourLips

https://symfony.com/doc/current/components/depend...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question