Service Provider

7/8/2021

# Description:

  • Nơi register service của application.
  • Linh động, dễ dàng thay thế, tích hợp service vào hệ thống.
  • Application sẽ duyệt qua các Service Provider để tiến hành binding service vào container.

Laravel Service Provider có rất nhiều service được khai báo tại config/app.php

# Config:

Tương tự như Laravel, tại Config/app.yml declare các service provider để application binding service vào container.

# app.yaml

services:
  - \Nin\Libs\Provider\RouteServiceProvider
1
2
3
4
// Application sẽ load qua các provider và thực hiện binding service

protected function loadServiceProvider(ConfigContract $config)
{
    $servicesProvider = $config->get('services');
    foreach ($servicesProvider as $service) {
        $provider = new $service($this);
        $provider->register();

        if (property_exists($provider, 'bindings')) {
            foreach ($provider->bindings as $key => $value) {
                $this->bind($key, $value);
            }
        }

        if (property_exists($provider, 'singletons')) {
            foreach ($provider->singletons as $key => $value) {
                $this->singleton($key, $value);
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Usage:

Tạo FooServiceProvider: có 2 dependency FooServiceInterface và FooRepositoryInterface

<?php

namespace Nin\Libs\Provider;

use Nin\Repositories\FooRepository;
use Nin\Repositories\FooRepositoryInterface;
use Nin\Services\FooService;
use Nin\Services\FooServiceInterface;

class FooServiceProvider extends AbstractServiceProvider
{
    protected $bindings = [
        FooServiceInterface::class => FooService::class,
        FooRepositoryInterface::class => FooRepository::class
    ];

  ...

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Khai báo config:

services:
  - \Nin\Libs\Provider\FooServiceProvider
1
2

FooRepository:

class FooRepository implements FooRepositoryInterface
{
    protected FooServiceInterface $fooService;

    public function __construct(FooServiceInterface $fooService)
    {
        $this->fooService = $fooService;
    }

    public function getBar(): string
    {
        return $this->fooService->getBar();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

FooService:

class FooService implements FooServiceInterface
{
    public function getBar()
    {
        return "bar";
    }
}
1
2
3
4
5
6
7

FooController:


namespace Nin\Controllers;

use Nin\Repositories\FooRepositoryInterface;

class FooController
{
    protected FooRepositoryInterface $fooRepository;

    public function __construct(FooRepositoryInterface $fooRepository)
    {
        $this->fooRepository = $fooRepository;
    }

    public function indexAction()
    {
		return $this->fooRepository->getBar();
    }
}
// output: "bar"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Packagist: https://packagist.org/packages/nin/nin (opens new window)