Service Providers

IOC Container

The inversion of control container

Helps us manage our dependenies and serve up the appropirate one for your app run time

Easily swap out your dependeny implementations

FooRepository

Why is this awesome?

class Foo {

    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }

}

Out of the box

$foo = App::make('foo');

Why is this awesome?

class Foo {

    public function __construct(Bar $bar, Baz $baz)
    {
        $this->bar = $bar;
        $this->baz = $baz;
    }

}

$foo = App::make('foo');

Using Laravel

The old fashion way

$bar = new Bar();

$baz = new Baz();

$foo = new Foo($bar, $baz);

Again this is out of the box!

Types of Bindings

Type Binding

App::bind('foo', function($app) {
    return new Foo();
});
App::singleton('foo', function($app) {
    return new Foo();
});
$foo = new Foo($attributes);

App::instance('foo', $foo);

Singleton Binding

Instance Binding

Service Providers

Provide a way for us to group related bindings in a central location. 

Most of Laravel's components utilize service providers  

https://github.com/illuminate/

app/config/app.php

'providers' => [
    'Illuminate\Foundation\Providers\ArtisanServiceProvider',
    'Illuminate\Auth\AuthServiceProvider',
    'Illuminate\Cache\CacheServiceProvider',
     
     ...
],

So how do we set this up?

1. Create a class that extends the Illuminate\Support\ServiceProvider class

use Illuminate\Support\ServiceProvider;

class FooServiceProvider extends ServiceProvider {

}

2. Define a register method.

use Illuminate\Support\ServiceProvider;

class FooServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('foo', function()
        {
            return new Foo;
        });
    }

}

3. Finally, just add your provider to app.php providers array.

Other Uses

View Composers

View::composer('foo', 'FooComposer');

Event Handlers

Event::listen('foo', 'FooHandler');

Filters

Route::filter('foo', 'FooFilter');

FIN

Damien Russell

 

Service Providers

By Damien Russell

Service Providers

  • 997