自己写的 provider,是 bind 还是 singleton 来绑定呢
1.自己原来写的provider里register方法里用bind绑定的,现在有时间优化代码,感觉是不是应该用singleton呢。感觉应该都用单例来绑定啊。
2.如果是用singleton来绑定,bind又是什么场景用呢。
3.以下代码哪个是比较好的改动方法呢?或者还有更好的方法,请多多指教。
```php
//旧代码
$this->app->bind(
'App\Repository\User\UserRepositoryContract',
'App\Repository\User\UserRepository'
);
//第一种改法
$this->app->bind('App\Repository\User\UserRepositoryContract', function () {
return new UserRepository();
});
//第二种改法
$this->app->bind('App\Repository\User\UserRepositoryContract', function () {
return $this->app->make(UserRepository::class);
});
//第三种改法
$this->app->bind('App\Repository\User\UserRepositoryContract', function () {
return app(UserRepository::class);
});
//第四种改法
$this->app->singleton('App\Repository\User\UserRepositoryContract', function () {
return new UserRepository();
});
//第五种改法
$this->app->singleton('App\Repository\User\UserRepositoryContract', function () {
return $this->app->make(UserRepository::class);
});
//第六种改法
$this->app->singleton('App\Repository\User\UserRepositoryContract', function () {
return app(UserRepository::class);
});
```
单例模式一般建议使用在 配置类 等类似地方,还有连接池啥的, 业务相关的对象 bind 比较好吧。