Well sorry to bump this thread. I am thinking about using a dependency injection container myself as well, so I can inject required dependencies into my controller and repository classes easily. The idea is that, my controller classes usually depend on one or multiple repository objects, while certain repository objects may also depend on other repository objects(if theres a foreign key). Below is an example that demonstrate that(I only show the constructors since these are the only one that matter):
class UserRepository{
public function __construct(PDO $database){
$this->database = $pdo;
}
}
class PostRepository{
public function __construct(PDO $database, UserRepository $userRepository){
$this->database = $database;
$this->userRepository = $userRepository;
}
}
class CommentRepository{
public function __construct(PDO $database, UserRepository $userRepository, PostRepository $postRepository){
$this->database = $database;
$this->userRepository = $userRepository;
$this->postRepository = $postRepository;
}
}
class PostController{
public function __construct(UserRepository $userRepository, PostRepository $postRepository, CommentRepository $commentRepository){
$this->userRepository = $userRepository;
$this->postRepository = $postRepository;
$this->commentRepository = $commentRepository;
}
}
As you see, the dependency graph is kinda strange, largely because a comment has foreign keys user(poster) and post(where the comments belong), and post has foreign key user(poster). For this reason, the PostRepository depends on UserRepository, and CommentRepository depend on User and Post repositories.
If I use a dependency injection container, such as Dice, I will need to configure the dependencies using rules. Since I want the PDO, UserRepository, and PostRepository injected into the Controller and CommentRepository to be the same instance, while by default all DICs will just create new instances. The question is, where do I put my DIC configuration logic? If my Dispatcher class is responsible for creating controllers, should I put such logic inside the dispatcher? But imagine I have like 20 controllers and 50 repositories, the configuration logic will be very very long, using a single method for this will make it a God class with long method with more than 1000 lines of code.
Another question is, since my controller class depends on CommentRepository, which depends on PostRepository, which in turn depends on UserRepository, may I just inject the CommentRepository and get the other dependencies from the CommentRepository. But does this violate good OO design principles? It feels like courier antipattern to me. What do you think?