I'll give a basic example, let's say I have 3 classes - Config
, Database
and User
. User
needs Database
and Database
needs Config
, but User
might also need Config
. All of the classes are going to need just one instance because I need to load the config file just once, connect to the database just once and check if the user is logged in and get their data just once. Now, what would be the best way to tell from within each class which classes it will need and have them load automatically? Or is this bad practice and I'm just being lazy? I tried making all classes singletons and accessing them like this from within each class:
User.php
$this->db = Module::get('Database');
But then I had to create a custom __construct()
method and have that run whenever I made a new instance of a class for the first time, which felt off-putting. I did some research and read that singletons
aren't exactly good practice and dependency-injection
would be a better solution, however I have no idea how to achieve this with dependency-injection
. So I'm wondering, is this even a good idea or should I re-think how I want everything to work?