服务容器 #

一、服务容器概述 #

1.1 什么是服务容器 #

服务容器是管理类依赖和执行依赖注入的工具。

text
服务容器作用
├── 依赖注入
│   └── 自动解析依赖
├── 服务绑定
│   └── 注册服务到容器
├── 服务解析
│   └── 从容器获取服务
└── 生命周期管理
    └── 单例、作用域等

1.2 获取容器实例 #

php
// 全局辅助函数
$container = app();

// 应用实例
$container = app('app');

// 在服务提供者中
$this->app;

二、服务绑定 #

2.1 简单绑定 #

php
app()->bind('service', function ($app) {
    return new Service();
});

2.2 单例绑定 #

php
app()->singleton('service', function ($app) {
    return new Service();
});

2.3 实例绑定 #

php
$service = new Service();
app()->instance('service', $service);

2.4 绑定接口到实现 #

php
app()->bind(
    PaymentInterface::class,
    StripePayment::class
);

2.5 上下文绑定 #

php
app()->when(UserController::class)
    ->needs(PaymentInterface::class)
    ->give(StripePayment::class);

app()->when(AdminController::class)
    ->needs(PaymentInterface::class)
    ->give(PaypalPayment::class);

2.6 绑定原始值 #

php
app()->when(UserController::class)
    ->needs('$timeout')
    ->give(30);

2.7 绑定闭包 #

php
app()->bind('service', function ($app) {
    return new Service($app->make(Config::class));
});

三、服务解析 #

3.1 make方法 #

php
$service = app()->make('service');
$service = app('service');
$service = resolve('service');

3.2 自动解析 #

php
class UserController extends Controller
{
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
}

3.3 注入容器 #

php
app()->call(function (UserService $userService) {
    // 自动注入
});

四、绑定类型 #

4.1 bind #

每次解析都创建新实例:

php
app()->bind('service', function () {
    return new Service();
});

$service1 = app('service');
$service2 = app('service');
// $service1 !== $service2

4.2 singleton #

只创建一次实例:

php
app()->singleton('service', function () {
    return new Service();
});

$service1 = app('service');
$service2 = app('service');
// $service1 === $service2

4.3 scoped #

同一请求内是单例:

php
app()->scoped('service', function () {
    return new Service();
});

4.4 instance #

绑定已存在的实例:

php
$service = new Service();
app()->instance('service', $service);

五、服务提供者 #

5.1 创建服务提供者 #

bash
php artisan make:provider PaymentServiceProvider

5.2 注册服务 #

php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class PaymentServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(PaymentInterface::class, function ($app) {
            return new StripePayment(config('services.stripe.key'));
        });
    }

    public function boot()
    {
        // 启动逻辑
    }
}

5.3 注册服务提供者 #

php
// config/app.php
'providers' => [
    // ...
    App\Providers\PaymentServiceProvider::class,
],

5.4 延迟加载 #

php
class PaymentServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->app->bind(PaymentInterface::class, StripePayment::class);
    }

    public function provides()
    {
        return [PaymentInterface::class];
    }
}

六、标签 #

6.1 定义标签 #

php
app()->bind('cache.fast', function () {
    return new FastCache();
});

app()->bind('cache.slow', function () {
    return new SlowCache();
});

app()->tag(['cache.fast', 'cache.slow'], 'caches');

6.2 解析标签 #

php
$caches = app()->tagged('caches');

foreach ($caches as $cache) {
    $cache->flush();
}

七、容器事件 #

7.1 解析事件 #

php
app()->resolving(function ($object, $app) {
    // 每次解析时调用
});

app()->resolving(PaymentInterface::class, function ($payment, $app) {
    // 解析特定类型时调用
});

八、实战示例 #

8.1 支付服务 #

php
// 接口
interface PaymentInterface
{
    public function charge($amount);
}

// 实现
class StripePayment implements PaymentInterface
{
    public function charge($amount)
    {
        // Stripe处理
    }
}

// 服务提供者
class PaymentServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(PaymentInterface::class, function ($app) {
            return new StripePayment(config('services.stripe.key'));
        });
    }
}

// 使用
class PaymentController extends Controller
{
    protected $payment;

    public function __construct(PaymentInterface $payment)
    {
        $this->payment = $payment;
    }

    public function charge($amount)
    {
        return $this->payment->charge($amount);
    }
}

8.2 仓储模式 #

php
// 接口
interface UserRepositoryInterface
{
    public function find($id);
    public function all();
}

// 实现
class UserRepository implements UserRepositoryInterface
{
    public function find($id)
    {
        return User::find($id);
    }

    public function all()
    {
        return User::all();
    }
}

// 绑定
app()->bind(UserRepositoryInterface::class, UserRepository::class);

// 使用
class UserService
{
    protected $repository;

    public function __construct(UserRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }
}

九、总结 #

9.1 核心方法 #

方法 说明
bind() 绑定服务
singleton() 单例绑定
instance() 实例绑定
make() 解析服务
when() 上下文绑定

9.2 下一步 #

掌握了服务容器后,让我们继续学习 事件系统,了解Laravel事件机制!

最后更新:2026-03-28