自己写的 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);
        });

```

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

单例模式一般建议使用在 配置类 等类似地方,还有连接池啥的, 业务相关的对象 bind 比较好吧。

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!