I understand the basic principles of dependency injection but would like some advice on how to handle classes instantiated within other classes methods; does this go against the dependency injection pattern?
Moreover, I would like to write the object (class) to a DB (mongo in object form) and so don't want it to be bloated with other dependencies.
To better explain what I mean here is an example:
Lets say we have a user class that gets injected with a server class -
class User{
public $user_id
public $user_name;
public function __construct(server $server){
$this->server = $server;
}
public function delete(){
//...delete user code
// Send mail to user
$mailer = new mailer($this->server);
$mailer->sendMail();
}
}
So two things about this
- This means that the User class now gets bloated as it contains the server class also
- Does this break the Law of Demeter? As the User class doesn't actually need the Server class other than to pass it onto the Mailer class..
I understand a way around this would be to inject the mailer class into the delete function when called from an outside controller, meaning the User class never has to be injected with the server class:
$server = new server();
$mailer = new mailer($server);
$user = new User();
$user->delete($mailer);
class User{
public $user_id
public $user_name;
public function __construct(){
// other code
}
public function delete(mailer $mailer){
//...delete user code
// Send mail to user
$mailer->sendMail();
}
}
But surely this means that you would need to know every class needed by methods within a class, if this nesting becomes a few levels deep surely this will be difficult to keep track of.
Also what happens if user->delete is a private method? You wouldn't be able to call it from an outside controller to pass in the mailer object in the first place.
So my question really is what's the best way of going about this?