laravel service provider 简单实例

1、创建服务类

Student.php

namespace AppServiceSchool;

class Student
{
    protected $TafficTool;

    function __construct(WayToSchool $foot)
    {
        $this->TafficTool = $foot;
    }

    public function goToSchool()
    {
        $this->TafficTool->goToSchool();
    }
}

  

WayToSchool.php
namespace AppServiceSchool;

interface WayToSchool
{
    public function goToSchool();
}

  

Foot.php

namespace AppServiceSchool;

class Foot implements WayToSchool
{

    public function goToSchool()
    {
        // TODO: Implement goToSchool() method.
        echo "walk to school";
    }
}

 

2、创建service provider

namespace AppProviders;
use AppServiceSchool;
use IlluminateSupportServiceProvider;

class StudentServiceProvider extends ServiceProvider
{

    protected $defer = false;
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {

        $this->app->singleton('student',function(){
            return new SchoolStudent(new SchoolBike());//不使用WayToSchoolServiceProvider.php  默认的 Foot,实现个性化的需求
        });

       //$this->app->singleton('Student',AppServiceSchoolStudent::class);//使用自动注入解决依赖
    }

}

WayToSchool.php

namespace AppProviders;
use AppServiceSchool;
use IlluminateSupportServiceProvider;

class WayToSchoolServiceProvider extends ServiceProvider
{

    public function register()
    {

        $this->app->singleton(SchoolWayToSchool::class,'AppServiceSchoolFoot');//接口 AppServiceSchoolWayToSchool 默认使用AppServiceSchoolFoot去实例化
    }

}

  

3、写到配置文件 config/app.php 的 providers数组

        AppProvidersWayToSchoolServiceProvider::class,
        AppProvidersStudentServiceProvider::class,

  

4、使用

routes/web.php

Route::get('std', function () {
    app('student')->goToSchool();
})

  

输出:by bike to school

 

原文地址:https://www.cnblogs.com/jinshao/p/15009026.html