I created a Laravel job for sending emails and I have multiple classes inheriting from Mailable
.
My Job class:
class SendMail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $emailObject;
public function __construct($emailObject)
{
$this->emailObject = $emailObject;
}
public function handle()
{
\Mail::to($this->emailObject->user->email)->queue($this->emailObject);
}
}
I execute this with:
$this->dispatch(new SendMail(new Profile($user)));
or
$this->dispatch(new SendMail(new Newsletter($user)));
I would like to create object or pattern which will allow me to create a constructor
with an object in my job. Like this:
class SendMail{
public function __construct(CommonMailObject $emailObject)
{
$this->emailObject = $emailObject;
}
}
eg. Profile class:
class Profile extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function build()
{
return $this->from('', '')
->subject('')
->view(EmailType::PROFILE);
}
}
You should just declare that your SendMail
class depends on a Mailable
object.
E.g.:
class SendMail{
public function __construct(Mailable $mailable)
{
$this->emailObject = $mailable;
}
}
That way you can do both:
$this->dispatch(new SendMail(new Profile($user)));
and
$this->dispatch(new SendMail(new Newsletter($user)));
In the Mailable class most properties are public. To get the address you need to get the to
property, which is an array (because it can handle multiple email addresses).
So you'd just have to access:
$this->emailObject->to
Haven't tested it, but probably:
\Mail::to($this->emailObject->to)->queue($this->emailObject);
should work.
I'll leave the fine-tuning to you.