Laravel Service Provider

정종일·2023년 10월 10일

Laravel

목록 보기
7/9
💡 Service Provider는 모든 라라벨 애플리케이션의 중심이 되는 기능이다. 라라벨의 모든 중요 기능들이 Service Provider를 통해 등록된다.

config/app.php 내부의 providers 배열에 provider 클래스들을 등록해 사용한다

Writing Service Providers

JPA

모든 service provider들은 Illuminate\Support\ServiceProvider를 상속받는다. service provider의 register 메서드에는 service container 내 항목만 바인딩해야 한다. 이외의 이벤트 리스너나 라우터 등은 register에 바인딩하면 안 된다.

php artisan make:provider RiakServiceProvider
// service provider 생성

The Register Method

<?php
 
namespace App\Providers;
 
use App\Services\Riak\Connection;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
 
class RiakServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(Connection::class, function (Application $app) {
            return new Connection(config('riak'));
        });
    }
}

The bindings And singleton Properties

여러 프로퍼티와 바인딩을 한 번에 처리하고 싶다면 아래와 같이 사용할 수 있다. service provider가 프레임워크로부터 로드될 때 자동으로 프로퍼티와 레지스터를 스캔해 등록한다

<?php
 
namespace App\Providers;
 
use App\Contracts\DowntimeNotifier;
use App\Contracts\ServerProvider;
use App\Services\DigitalOceanServerProvider;
use App\Services\PingdomDowntimeNotifier;
use App\Services\ServerToolsProvider;
use Illuminate\Support\ServiceProvider;
 
class AppServiceProvider extends ServiceProvider
{
    /**
     * All of the container bindings that should be registered.
     *
     * @var array
     */
    public $bindings = [
        ServerProvider::class => DigitalOceanServerProvider::class,
    ];
 
    /**
     * All of the container singletons that should be registered.
     *
     * @var array
     */
    public $singletons = [
        DowntimeNotifier::class => PingdomDowntimeNotifier::class,
        ServerProvider::class => ServerToolsProvider::class,
    ];
}

The Boot Method

boot 메서드는 모든 register 메서드가 실행된 후 실행되기 때문에 등록된 모든 서비스에 접근할 수 있다

<?php
 
namespace App\Providers;
 
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
 
class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        View::composer('view', function () {
            // ...
        });
    }
}

Boot Method Dependency Injection

boot 메서드에 타입 힌트로 의존성을 주입하면 서비스 컨테이너가 자동으로 매핑에 의존성을 주입해준다

use Illuminate\Contracts\Routing\ResponseFactory;
 
/**
 * Bootstrap any application services.
 */
public function boot(ResponseFactory $response): void
{
    $response->macro('serialized', function (mixed $value) {
        // ...
    });
}

Registering Providers

'providers' => ServiceProvider::defaultProviders()->merge([
    // Other Service Providers
 
    App\Providers\ComposerServiceProvider::class,
])->toArray(),

Deferred Providers

서비스 컨테이너에만 바인딩한 경우 실제 사용이 되는 시점에만 load 하도록 lazy load가 가능하다

<?php
 
namespace App\Providers;
 
use App\Services\Riak\Connection;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;
 
class RiakServiceProvider extends ServiceProvider implements DeferrableProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(Connection::class, function (Application $app) {
            return new Connection($app['config']['riak']);
        });
    }
 
    /**
     * Get the services provided by the provider.
     *
     * @return array<int, string>
     */
    public function provides(): array
    {
        return [Connection::class];
    }
}
profile
제어할 수 없는 것에 의지하지 말자

1개의 댓글

comment-user-thumbnail
2025년 3월 28일

The final round in fall guys is definitely one of the most tense games, when only a few survivors are left to compete for the crown with all their ingenuity and a little luck. Will you be one of the lucky ones to own that crown?

답글 달기