| Registration name | Target name |
|---|---|
| Request | Illuminate/Http/Request |
| Illuminate/Mail/System |
public function myMethod() {
Mail::send('template', function(MailMessage $message) {
$message->setSubject(Request::get('subject');
$message->to(Request::get('to'));
});
}Facade usage
Constructor injection
public function __construct(Mail $mail) {
$this->mail = $mail;
}public function myMethod(Request $request) {
$this->mail->send('template', function() use ($request) {
$this->setSubject($request->get('subject');
$this->to($request->get('to'));
});
}Method injection
app::when(Controller::Class)
->needs('SomeName')
->give(SomeClassV2::class);
app::when(AnOldController::Class)
->needs('SomeName')
->give(SomeClassV1::class);Not at all, just less direct.
They are a simpler and cleaner approach to accessing globally available libraries.
They are much better than singletons
or static bindings!
class MySingleton {
public static function myAwesomeStaticFunction() { ... }
}
MySingleton::myAwesomeStaticFunction();class MyClass {
public function myAwesomeFunction() { ... }
}
That::myAwesomeFunction();'aliases' => [
'Riddles' => App\ServicesProviders\RiddlesServiceProvider
\Facades\Riddles::class,
]class Riddles extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'Riddles';
}
}class RiddlesServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
$this->app->bind('Riddles', function ($app) {
return new RiddleRepository();
});
}
}class RiddleRepository {
public function getARiddle() : Riddle { ... }
}
$riddle = Riddle::getARiddle();$this->app->bind(
EmailAggregatorInterface::class, ReviewerIDBasedEmailAggregator::class
);
$this->app->bind(
EmailTargetInterface::class, LessonReviewCreatorEmailTarget::class
);
$this->app->bind(
EmailDeciderInterface::class, ImmediatelySentEmailDecider::class
);$this->app->tag(
JiraSummaryConsoleCommand::class, ['ConsoleCommand']
);
$this->app->tag(
JiraSprintsConsoleCommand::class, ['ConsoleCommand']
);
$this->app->tag(
JiraBugsConsoleCommand::class, ['ConsoleCommand']
);You can use the container outside of laravel
composer require illuminate/container$ioc = new Illuminate\Container\Container();// Send an email for each user that asked for news
foreach($users as $user) {
Mail::send('template', function() use ($user) {
$this->setTo($user->email);
$this->setSubject(Request::get('subject');
});
}It locks up your response!
Mail::queue('template', function(MailMessage $message){
$message->to('someone@else.com');
});
dispatch(new UploadProcessingJob(
$fileToProcess,
$uploadingUser
));Service container can define jobs and can even queue their own jobs...
class SendReminderEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function handle(Mailer $mailer)
{
$mailer->send(/* ... */);
$this->user->reminders()->create(...);
}
}php artisan queue:work --queue=emails
php artisan queue:work redis --queue=jobs
php artisan queue:work sqs --queue=emails
php artisan queue:work --sleep 3Server 1
Server 2
Server 3
Runs web requests
Runs the email queue
Runs the upload processing job queue
$job->onQueue('low');
$job->onConnection('slow-queues');$checkTranscodingJobIsDone->delay(Carbon::now()->addMinutes(10));
$sendAppreciationEmail->delay(Carbon::now()->addDays(5));You can use the queue outside of laravel
composer require illuminate/queueNote: Not an easy thing to do though!
First you need to create event objects
<?php
namespace App\Events;
class AnswerCreatedEvent extends Event
{
use Illuminate\Queue\SerializesModels;
public $answer;
public function __construct(App\Answer $answer)
{
$this->answer = $answer;
}
}Then you need to create event listeners
<?php
namespace App\Listeners;
class NotifyClubOwnerOnAnswerCreatedListener {}
class NotifyRiddleOwnerOnAnswerCreatedListener {}
class AwardEarlyBirdBadgeOnEarlyAnswersListener {}
class AwardProcrastinatorBadgeOnLateAnswersListener {}
/**
* Each class implements
*/
public function handle(App/Events/AnswerCreatedEvent $event) {
// Do something
}Finaly, you need to bind events and listeners
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
AnswerCreatedEvent::class => [
NotifyClubOwnerOnAnswerCreatedListener::class,
NotifyRiddleOwnerOnAnswerCreatedListener::class,
AwardEarlyBirdBadgeOnEarlyAnswersListener::class,
AwardProcrastinatorBadgeOnLateAnswersListener::class,
],
];
}Once all is bounded, you can fire events away!
<?php
$answer = Answer::create([
'answer' => $answer,
'club_riddle_id' => $clubRiddle->id,
'user_id' => $user->id,
]);
Event::fire(new AnswerCreatedEvent($answer));This will fire the handle method of all 4 listeners in no specific order and not necessarily now...
class NotifyOwnerThatAnswerWasPosted implements ShouldQueue {}Do not assume that a listener has run at any moment unless you have data backing this decision.
You can use the events outside of laravel
composer require illuminate/eventsNote: Not an easy thing to do though!
public function scopeWithoutActiveRiddleFor($query, Carbon $date)
{
$query
->select('clubs')
->leftJoin('clubs_riddles', function (JoinClause $on) use ($date) {
$on->on('clubs_riddles.club_id', '=', 'clubs.id');
$on->where('clubs_riddles.opens_at', '>=', $date->copy()->startOfDay()->tz('UTC'));
$on->where('clubs_riddles.opens_at', '<=', $date->copy()->endOfDay()->tz('UTC'));
})
->whereNull('clubs_riddles.riddle_id');
}public function achievements()
{
return $this->belongsToMany(Achievement::class)->withPivot(['current']);
}
public function badges()
{
return $this->belongsToMany(Badge::class)->withPivot('amount');
}$value = $record->pivot->column;$riddle->creator->badges()->updateExistingPivot(
$badge->id,
['amount' => $record->pivot->amount + 1]
);$riddle->creator->badges()->attach(
$badge,
['amount' => 1]
);public function currentAchievement()
{
return $this->belongsToMany(Achievement::class)
->where('current', 1);
}class Answer
{
use Notifiable;
protected $events = [
'created' => AnswerCreatedEvent::class,
];
}$answer = Answer::create([
'answer' => $answer,
'club_riddle_id' => $clubRiddle->id,
'user_id' => $user->id,
]);
Event::fire(new AnswerCreatedEvent($answer));public function getScoreAttribute($score)
{
return $score * 100
}
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
public function setAvailabilityAttribute($value)
{
$this->attributes['availability'] = $value;
}protected $appends = ['someVirtualProperty'];
protected $hidden = ['password'];Senior Dev @ Learning Bird
Twitter: @thecrazycodr
LinkedIn: @crazycoders
GitHub: @crazycodr
Email: thecrazycodr@gmail.com
Open source contributions
Contact me
Standard-Exceptions 2.0: GitHub