laravel 注册的服务是可以延时加载的

很简单,在provider文件夹下指定的服务当中这样写

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace App\Providers;

use App\Repositories\RecommendRepository;
use Illuminate\Support\ServiceProvider;

class HotcastProvider extends ServiceProvider
{
    /**
     * 服务提供者加是否延迟加载.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

        $this->app->bind('App\Repositories\Contract\RecommendInterface','App\Repositories\RecommendRepository');

        $this->app->singleton('RecommendFacade',function (){
            return new RecommendRepository();
        });

    }

    /**
     * 获取由提供者提供的服务.
     *
     * @return array
     */
    public function provides()
    {
        return ['RecommendFacade','App\Repositories\Contract\RecommendInterface'];
    }
}

defer 改为 true, 添加一个 provides方法,然后命令行执行php artisan clear-compiled 重新编译一下服务文件就OK了