-
-
Save adamwathan/2ccbc0f6fe3f3b31ed3d to your computer and use it in GitHub Desktop.
Dealing with Dependencies in Active Record Models — Option #3: Composing a new domain object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// The Domain Object | |
class Invitation | |
{ | |
private $invitationRecord; | |
private $mailer; | |
public function __construct(InvitationRecord $invitationRecord, Mailer $mailer) | |
{ | |
$this->invitationRecord = $invitationRecord; | |
$this->mailer = $mailer; | |
} | |
public function send() | |
{ | |
$this->mailer->send('emails.invitation', ['invited_by' => $this->invitationRecord->user], function ($m) { | |
$m->to($this->invitationRecord->recipient)->subject("You've been invited to my app!"); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class InvitationBuilder | |
{ | |
private $mailer; | |
public function __construct(Mailer $mailer) | |
{ | |
$this->mailer = $mailer; | |
} | |
public function create($recipient, $invitedBy) | |
{ | |
$invitationRecord = InvitationRecord::create([ | |
'recipient' => $recipient, | |
'invited_by' => $invitedBy->id, | |
]); | |
return new Invitation($invitationRecord, $this->mailer); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// The Active Record model | |
class InvitationRecord extends Model | |
{ | |
protected $table = 'invitations'; | |
public function user() | |
{ | |
return $this->belongsTo(User::class, 'invited_by'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class InvitationsController extends Controller | |
{ | |
private $invitationBuilder; | |
public function __construct(InvitationBuilder $invitationBuilder) | |
{ | |
$this->invitationBuilder = $invitationBuilder; | |
} | |
public function store() | |
{ | |
$recipient = request('recipient'); | |
$invitedBy = auth()->user(); | |
$invitation = $this->invitationBuilder->create($recipient, $invitedBy); | |
$invitation->send(); | |
return response('', 204); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment