Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active February 2, 2016 07:27
Show Gist options
  • Save adamwathan/09e41497dbd263caaf6c to your computer and use it in GitHub Desktop.
Save adamwathan/09e41497dbd263caaf6c to your computer and use it in GitHub Desktop.
Dealing with Dependencies in Active Record Models — Option #4a: Using method injection
<?php
class Invitation extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'invited_by');
}
public function send(Mailer $mailer)
{
$mailer->send('emails.invitation', ['invited_by' => $this->user], function ($m) {
$m->to($this->recipient)->subject("You've been invited to my app!");
});
}
}
<?php
class InvitationsController extends Controller
{
private $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function store()
{
$invitation = Invitation::create([
'recipient' => request('recipient'),
'invited_by' => auth()->user()->id,
]);
$invitation->send($this->mailer);
return response('', 204);
}
}
@mrsimonbennett
Copy link

Has my vote

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment