Skip to content

Instantly share code, notes, and snippets.

@Jatapiaro
Last active April 8, 2018 09:32
Show Gist options
  • Save Jatapiaro/dc2e3b12c1bd475109b1be48b8a59e6f to your computer and use it in GitHub Desktop.
Save Jatapiaro/dc2e3b12c1bd475109b1be48b8a59e6f to your computer and use it in GitHub Desktop.

Creating services

This guide shows how to create services on the system.

Creation

  1. Create the service on app/Services, for example, create the file HistoryService.php
<?php
namespace App\Services;

class HistoryService
{
    public function foo() {

    }
}
  1. Create the Service Provider in app/Providers, for example:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\HistoryService;

class HistoryServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('HistoryService', function($app)
        {
            return new HistoryService();
        });
    }
}
  1. Create the Facade to access that service in app/Facades, for example:
<?php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class HistoryFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'HistoryService';
    }
}
  1. Register the service provider on config/app.php, for example:
<?php
return [
     // ... a lot of things
    'providers' => [
         // ... a lot of things
         App\Providers\HistoryServiceProvider::class,
     ],
     // ... a lot of things
     'aliases' => [
         // ... a lot of things
         'HistoryService' => App\Facades\HistoryFacade::class,
     ]
]

Usage

<?php
namespace App;

use App\Facades\HistoryFacade; // Important!

class Something {
   public function bar() {
       HistoryFacade::foo(); // Important!
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment