Laravel TutorialChange default routing behaviour in Laravel 5.2.31 +CustomException class in LaravelDeploy Laravel 5 App on Shared Hosting on Linux ServerLaravel ArtisanLaravel AuthenticationLaravel AuthorizationLaravel Blade TemplatesLaravel CashierLaravel CollectionsLaravel Common Issues & Quick FixesLaravel ConstantsLaravel ControllersLaravel Cron basicsLaravel Cross Domain RequestLaravel Custom Helper functionLaravel DatabaseLaravel Database MigrationsLaravel Database SeedingLaravel Directory StructureLaravel DockerLaravel EloquentLaravel Eloquent : RelationshipLaravel Eloquent: Accessors & MutatorsLaravel Eloquent: ModelLaravel Error HandlingLaravel Events and ListenersLaravel Filesystem / Cloud StorageLaravel Form Request(s)Laravel Getting started with laravel-5.3Laravel HelpersLaravel HTML and Form BuilderLaravel InstallationLaravel Installation GuideLaravel Introduction to laravel-5.2Laravel Introduction to laravel-5.3Laravel lumen frameworkLaravel Macros in Eloquent RelationshipLaravel MailLaravel MiddlewareLaravel ObserverLaravel PackagesLaravel PaginationLaravel Permissions for storageLaravel PoliciesLaravel QueuesLaravel RequestsLaravel Route Model BindingLaravel RoutingLaravel SeedingLaravel ServicesLaravel SocialiteLaravel Task SchedulingLaravel TestingLaravel Token Mismatch Error in AJAXLaravel use fields aliases in EloquentLaravel Useful linksLaravel ValetLaravel ValidationMultiple DB Connections in LaravelNaming Files when uploading with Laravel on WindowsRemove public from URL in laravelSparkpost integration with Laravel 5.4

Laravel Services

From WikiOD

Binding a Singleton to the Service Container[edit | edit source]

We can bind a class as a Singleton:

public function register()
    App::singleton('my-database', function()
        return new Database();

This way, the first time an instance of 'my-database' will be requested to the service container, a new instance will be created. All the successive requests of this class will get back the first created instance:

//a new instance of Database is created 
$db = App::make('my-database'); 

//the same instance created before is returned
$anotherDb = App::make('my-database');

Binding an Interface To Implementation[edit | edit source]

In a Service Provider register method we can bind an interface to an implementation:

public function register()
    App::bind( UserRepositoryInterface::class, EloquentUserRepository::class );        

From now on, everytime the app will need an instance of UserRepositoryInterface, Laravel will auto inject a new instance of EloquentUserRepository :

//this will get back an instance of EloquentUserRepository 
$repo = App::make( UserRepositoryInterface:class );

Using the Service Container as a Dependency Injection Container[edit | edit source]

We can use the Service Container as a Dependency Injection Container by binding the creation process of objects with their dependencies in one point of the application

Let's suppose that the creation of a PdfCreator needs two objects as dependencies; every time we need to build an instance of PdfCreator, we should pass these dependencies to che constructor. By using the Service Container as DIC, we define the creation of PdfCreator in the binding definition, taking the required dependency directly from the Service Container:

App:bind('pdf*creator', function($app) {

    // Get the needed dependencies from the service container.
    $pdfRender = $app->make('pdf-render');
    $templateManager = $app->make('template-manager');

    // Create the instance passing the needed dependencies.
    return new PdfCreator( $pdfRender, $templateManager );    

Then, in every point of our app, to get a new PdfCreator, we can simply do:

$pdfCreator = App::make('pdf-creator');

And the Service container will create a new instance, along with the needed dependencies for us.

Binding an Instance[edit | edit source]

We can use the Service Container as a Registry by binding an instance of an object in it and get it back when we'll need it:

// Create an instance.
$john = new User('John');

// Bind it to the service container.
App::instance('the*user', $john);

// ...somewhere and/or in another class...

// Get back the instance
$john = App::make('the-user');

Introduction[edit | edit source]

The Service Container is the main Application object. It can be used as a Dependency Injection Container, and a Registry for the application by defining bindings in the Service Providers

Service Providers are classes where we define the way our service classes will be created through the application, bootstrap their configuration, and bind interfaces to implementations

Services are classes that wrap one or more logic correlated tasks together