'from' => ['address' => 'yourmail@mail.com', 'name' => 'Your awesome app'],
Now we need to create an account in pusher.com and configure our app. After create pusher account, go to config/broadcasting.php and verify:
'default' => env('BROADCAST_DRIVER', 'pusher'),
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true
],
],
Don’t forget the options, cluster. Get this on pusher.com dashboard. Now we need to set our .env with info provided by pusher.com
PUSHER_KEY=25a75617457490364db66
PUSHER_SECRET=0eaab165d010e2626da4bb
PUSHER_APP_ID=222644517
Now, use composer to get the libs:
composer require pusher/pusher-php-server
After all this, we have our app set to code the main hand, go and create the listener and the event. Open EventServiceProvider and put the list/event:
protected $listen = [
'App\Events\SendEmailEvent' => [
'App\Listeners\SendEmailEventListener@sendEmail',
],
];
With this, we can generate the list/event:
php artisan event:generate
So, when the SendEmailEvent is called, the SendEmailEventListener will execute sendEmail(). Go and code SendEmailEvent:
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class SendEmailEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $richGuy;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($richGuy)
{
$this->richGuy = $richGuy;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return ['stock'];
}
}
We need to implement ShouldBroadcast to tell pusher-php that we will broadcast. In broadcastOn(), we specify the name of the channel (stock). We need use the SerializesModels trait because we will send the $richGuy attribute. Now, let’s code SendEmailEventListener:
<?php
namespace App\Listeners;
use App\Events\SendEmailEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
class SendEmailEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SendEmailEvent $event
* @return void
*/
public function sendEmail(SendEmailEvent $event)
{
$specialOffer = $event->richGuy;
Mail::send('emails.stock',
['specialOffer' => $specialOffer],
function ($message) use ($specialOffer) {
//$message->from('optional@gmail.com', 'Super Stock');
$message->to($specialOffer['email'], $specialOffer['name'])->subject($specialOffer['subject']);
}
);
//return false will stop propagation
}
}
In the sendEmail method, we put our logic to send email. We specify a view emails.stock with html for the email and an $specialOffer array that will be used in the stock email view. The $message->from() method is optional because we defined in config. The emails.stock view offer the stock for the client:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<h1>Buy this stock now</h1>
<h2>Code: {{ $specialOffer['stock']->getCode() }}</h2>
<h2>Price: {{ $specialOffer['stock']->getPrice() }}</h2>
<h2>Buy and be a rich guy!</h2>
</div>
</body>
</html>
Let’s define our routes.php:
Route::get('/', 'PagesController@welcome');
Route::get('analyzeStock', 'PagesController@analyzeStock');
Create the Stock class and in the PagesController code the analyzeStock method:
use App\Events\SendEmailEvent;
class Stock{
protected $price;//why protected?
protected $code;
public function __construct($price, $code){
$this->price = $price;
$this->code = $code;
}
public function getPrice(){
return $this->price;
}
public function getCode(){
return $this->code;
}
}
public function analyzeStock(){
//... analyzing stock
$mySpecialStock = new Stock(250, '4a9k1qui');
event(new SendEmailEvent( ['stock' => $mySpecialStock, 'subject'=>'Buy this stock now!', 'email' => 'stock@myapp.com', 'name' => 'Rich Guy'] ) );
return view('stocks.stockConfirmationView');
}
In the analyzeStock(), we call event(), passing the event and the constructor parameters. We protected $price and $code, later we’ll get back to this. We can show a confirmation building a simple view stocks.stockConfirmationView.
Last, code the client page that will receive information:
<script src="https://js.pusher.com/3.1/pusher.min.js"></script>
<script>
(function(){
var pusher = new Pusher('2575617457490364db66', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('stock');
console.log('Binding...');
channel.bind('App\\Events\\SendEmailEvent', function(data) {
console.log(data);
});
})();
</script>
We’ll load pusher.min.js and call a sia function to connect. Again, we need to put our key and cluster, all this available at pusher.com dashboard. Following, we’ll open our channel, stock, the same in the Event class and bind our event. Now we can open this page and see in the console the object sent. Every time, somebody hits /analyzeStock, an e-mail will be sent and the object will be sent to all pages with open channels, then you can use Knockout.js, jQuery and other cool things to show nice animations and updates to users. Now, think, why price and code in Stock are protected? What will happen if we change those for public?
TY, more info in:
https://pusher.com/
https://laravel.com/docs/5.2/mail
https://laravel.com/docs/5.2/events
https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/12
http://knockoutjs.com/