为什么实现了接口的类需要在 provider 里绑定,直接在使用的地方注入不也一样吗?
{tip} 如果某个容器不依赖于任何接口就没必要去绑定类在这个容器里。
文档里有这么一句话吸引了我的注意。就拿文档后面的例子来举例:$this->app->bind( 'App\Contracts\EventPusher', 'App\Services\RedisEventPusher' );
这样绑定一下的意义何在?
它的效果是:public function __construct(EventPusher $pusher) { $this->pusher = $pusher; }
这样注入EventPusher的时候(其实它是个接口),却实际注入了一个具体实现了的RedisEventPusher。
可我就是无法理解这样做的意义——既然绑定了RedisEventPusher到EventPusher上,让程序默认使用RedisEventPusher,那就说明,我只想用RedisEventPusher了,不会再有DbEventPusher、RabbitMQEventPusher等等实现了吧?那为啥还要绑定?为什么我不直接:public function __construct(RedisEventPusher $pusher) { $this->pusher = $pusher; }
当我想要用别的DbEventPusher的时候,我也可以:
public function __construct(DbEventPusher $pusher) { $this->pusher = $pusher; }
这样不是很好吗?
所以,哪位大神来给我解惑一下,这个bind的意义究竟是什么?
假如有 100 个类都需要 EventPusher 作为构造函数的参数,然后你想把 Redis 改成 DB,想想这个工作量就爽歪歪。