29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Service Container 126<br />

.<br />

1 use App\Contracts\EventPusher;<br />

2<br />

3 /**<br />

4 * Create a new class instance.<br />

5 *<br />

6 * @param EventPusher $pusher<br />

7 * @return void<br />

8 */<br />

9 public function __construct(EventPusher $pusher)<br />

10 {<br />

11 $this->pusher = $pusher;<br />

12 }<br />

Contextual Binding<br />

Sometimes you may have two classes that utilize the same interface, but you wish to inject different<br />

implementations into each class. For example, when our system receives a new Order, we may want<br />

to send an event via PubNub⁵⁴ rather than Pusher. Laravel provides a simple, fluent interface for<br />

defining this behavior:<br />

.<br />

1 $this->app->when('App\Handlers\Commands\CreateOrderHandler')<br />

2 ->needs('App\Contracts\EventPusher')<br />

3 ->give('App\Services\PubNubEventPusher');<br />

You may even pass a Closure to the give method:<br />

.<br />

1 $this->app->when('App\Handlers\Commands\CreateOrderHandler')<br />

2 ->needs('App\Contracts\EventPusher')<br />

3 ->give(function () {<br />

4 // Resolve dependency...<br />

5 });<br />

⁵⁴http://www.pubnub.com/

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!