JoshWilley
5 years ago

Dependency Injection and Reflection

Posted 5 years ago by JoshWilley

How do you guys handle dependency injection and class reflection when dealing with class inheritance?

Here's an example:

abstract class Mailer {

    /**
     * @var \Illuminate\Mail\Mailer
     */
    private $mailer;

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


    /**
     * Send an email
     *
     * @param $emailAddresses
     * @param $subject
     * @param $view
     * @param array $data
     */
    public function send($emailAddresses, $subject, $view, $data = [])
    {
        $recipients = $this->resolveEmailAddresses($emailAddresses);

        $this->mailer->send($view, $data, function ($message) use ($recipients, $subject)
        {
            $message->to($recipients->get('to'))->cc($recipients->get('cc'))->bcc($recipients->get('bcc'))->subject($subject);
        });
    }
}
class RegistrationMailer extends Mailer {

    /**
     * @var \Illuminate\Auth\Reminders\PasswordBroker
     */
    private $password;

    /**
     * @param PasswordBroker $password
     */
    function __construct(PasswordBroker $password)
    {
        // This constructor overrides the parent's constructor, so Illuminate's Mailer class is never injected.
        // The work around here is to call "parent::__construct()"
        // But now you've lost the advantage of the reflection API, as far as I know.
        $this->password = $password;
    }

    /**
     * Send a password reminder email to a user.
     *
     * @param array $credentials
     */
    public function remind(array $credentials)
    {
        $this->password->remind($credentials);
    }
}

The comments in the last class constructor illustrates my problem.

Does anyone have a clean solution for this?

Please sign in or create an account to participate in this conversation.