laravel的ioc容器——service provider使用

721 查看

1.在app目录下新建自己的文件夹及文件

app目录下,有一个我自己建的Serveice/HelloService.php

<?php
class HelloService
{

    public function index($name)
    {
        dd('say hi '.$name);
    }
}

2.在artisan命令,新建一个provider,文件存放在app/Provider下

php artisan make:provider HelloServiceProvider

3.在register方法中写绑定操作

public function register()
{
        //使用singleton绑定单例
        $this->app->singleton('hello',function(){
            // return new HelloService();
            return new HelloService();
        });

        //使用bind绑定实例到接口以便依赖注入
//        $this->app->bind('App\Service\HelloService',function(){
//            return new HelloService();
//        });
}

4.调用,在routes.php路由中之间调用

Route::get('/', function () {
    // 读取single单例绑定的对象
    // 1.make方式,
    // dd( app()->make('hello') );
    // 2.数组方式
    // dd( app()['hello'] );
    // 3.参数方式
    // dd( app('hello') );

    // 调用bind方法调用绑定的对象
    // dd(app('hello'));

    $hello= app('hello');
    $hello->index('zhengcheng');
});