Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Created January 27, 2016 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamwathan/feaa708369450376b404 to your computer and use it in GitHub Desktop.
Save adamwathan/feaa708369450376b404 to your computer and use it in GitHub Desktop.
Dealing with Dependencies in Active Record Models — Option #2: Using a new object
<?php
class Invitation extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'invited_by');
}
}
<?php
class InvitationsController extends Controller
{
private $invitationSender;
public function __construct(InvitationSender $invitationSender)
{
$this->invitationSender = $invitationSender;
}
public function store()
{
$invitation = Invitation::create([
'recipient' => request('recipient'),
'invited_by' => auth()->user()->id,
]);
$this->invitationSender->send($invitation);
return response('', 204);
}
}
<?php
class InvitationSender
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function send($invitation)
{
$this->mailer->send('emails.invitation', ['invited_by' => $invitation->user], function ($m) use ($invitation) {
$m->to($invitation->recipient)->subject("You've been invited to my app!");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment