用一句人话说:容器就是那个「帮你 new 对象,顺便把它依赖的对象也 new 好」的东西。

从一个 Controller 说起

假设我们有一个下单接口,需要调用支付网关:

class OrderController extends Controller
{
    public function store(Request $request)
    {
        $gateway = new AlipayGateway(new HttpClient(), config('pay.alipay'));
        $result = $gateway->pay($request->integer('amount'));
    }
}

这段代码在项目小的时候没问题,但它把三件事绑死在了一起:

  1. Controller 知道了「用支付宝」这个实现细节;
  2. Controller 知道了 AlipayGateway 需要哪些依赖;
  3. 想换成微信支付或者做单元测试,必须改源码。

容器解决的正是第 2 点——谁需要什么,由谁自己声明,而不是由调用方拼装。

绑定:告诉容器「怎么造」

在 AppServiceProvider 里注册:

public function register(): void
{
    // 每次解析都创建一个新实例
    $this->app->bind(PaymentGateway::class, AlipayGateway::class);

    // 整个生命周期只创建一个实例(连接池、配置对象适合用这个)
    $this->app->singleton(RedisClient::class, function ($app) {
        return new RedisClient($app['config']['database.redis']);
    });
}

绑定之后,Controller 只依赖接口:

class OrderController extends Controller
{
    public function store(Request $request, PaymentGateway $gateway)
    {
        return $gateway->pay($request->integer('amount'));
    }
}

Laravel 在解析 Controller 时发现构造/方法参数里有 PaymentGateway,就会去容器里查绑定,拿到实现并注入进来。

解析:从容器里拿对象

除了自动注入,也可以手动拿:

$gateway = app(PaymentGateway::class);
$gateway = resolve(PaymentGateway::class);

自动注入能覆盖 90% 的场景,剩下 10% 是「运行时才能决定用哪个实现」,比如按渠道选择支付方式:

$this->app->when(OrderController::class)
    ->needs(PaymentGateway::class)
    ->give(function () {
        return match (request('channel')) {
            'wechat' => new WechatGateway(),
            default  => new AlipayGateway(),
        };
    });

这就是上下文绑定:同一个接口,在不同类里注入不同的实现。

常见误区

误区 说明
什么都往容器里塞 只有「有依赖、需要替换、需要共享」的对象才值得注册
用单例存请求数据 单例跨请求复用会串数据,请求相关的一律用 bind 或直接传参
在构造函数里做 IO 容器解析发生在请求早期,构造里连数据库会拖慢所有请求
忘记接口绑定 注入接口但没绑定,会抛 Target [X] is not instantiable

一个最小的容器实现

理解容器最好的方式是手写一个:

class Container
{
    protected array $bindings = [];
    protected array $instances = [];

    public function bind(string $abstract, Closure $concrete): void
    {
        $this->bindings[$abstract] = $concrete;
    }

    public function make(string $abstract)
    {
        if (isset($this->instances[$abstract])) {
            return $this->instances[$abstract];
        }

        $concrete = $this->bindings[$abstract] ?? $abstract;

        if ($concrete instanceof Closure) {
            return $this->instances[$abstract] = $concrete($this);
        }

        $reflection = new ReflectionClass($concrete);
        $constructor = $reflection->getConstructor();

        if (! $constructor) {
            return new $concrete;
        }

        $dependencies = array_map(
            fn (ReflectionParameter $param) => $this->make($param->getType()->getName()),
            $constructor->getParameters()
        );

        return $reflection->newInstanceArgs($dependencies);
    }
}

不到 40 行,核心逻辑就是「反射看构造函数 → 递归解析参数 → new 出来」。

小结

  • 容器 = 自动装配 + 可替换的绑定表;
  • bind 用于每次新建,singleton 用于全局共享;
  • 需要按场景切换实现时用上下文绑定;
  • 不要为了用容器而用容器,简单的值对象直接 new 更清晰。
本文由 Devin 整理发布于 IT 笔记, 采用 CC BY-NC-SA 4.0 许可协议, 转载请注明出处。