29.07.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Service Container 127<br />

Tagging<br />

Occasionally, you may need to resolve all of a certain “category” of binding. For example, perhaps<br />

you are building a report aggregator that receives an array of many different Report interface<br />

implementations. After registering the Report implementations, you can assign them a tag using<br />

the tag method:<br />

.<br />

1 $this->app->bind('SpeedReport', function () {<br />

2 //<br />

3 });<br />

4<br />

5 $this->app->bind('MemoryReport', function () {<br />

6 //<br />

7 });<br />

8<br />

9 $this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');<br />

Once the services have been tagged, you may easily resolve them all via the tagged method:<br />

.<br />

1 $this->app->bind('ReportAggregator', function ($app) {<br />

2 return new ReportAggregator($app->tagged('reports'));<br />

3 });<br />

Resolving<br />

There are several ways to resolve something out of the container. First, you may use the make method,<br />

which accepts the name of the class or interface you wish to resolve:<br />

.<br />

1 $fooBar = $this->app->make('FooBar');<br />

Secondly, you may access the container like an array, since it implements PHP’s ArrayAccess<br />

interface:<br />

.<br />

1 $fooBar = $this->app['FooBar'];

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

Saved successfully!

Ooh no, something went wrong!