The problem you are having is Injection of Dependency .
The dependency of a class occurs when you "inject", passing one class to be worked within the other.
This means that in order for there to be a dependency injection, the instantiation of an object should not occur within the class, but outside the class and then injected.
One of the ways to accomplish this is to inject the external class through the constructor method .
Let's go to the example:
<?php
class Email
{
public function send()
{
// TODO
}
}
class Usuario
{
protected $email;
//Injeção de dependência através do método construtor
public function __construct(Email $email)
{
$this->email = $email;
}
public function porEmail()
{
$this->email->send();
}
}
__ construct () is how you declare a constructor method in PHP, unlike languages like Java where you use the same class name, for example: public User ().
Note that now when calling method $command->porEmail()
we are actually triggering the send()
method of class $email
, for example, we can do this:
$email = new email();
$anunciar = new Usuario($email);
$anunciar->porEmail();
Note that the Usuario
class receives by injection $email
. This whole process we have done means dependency injection. See how simple?