• 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

     

  • 相关阅读:
    树链剖分学习笔记(未完)
    VI 配置文件(略全)
    linux之awk
    指针之基础篇
    linux之sed
    sqlplus命令手册
    Leetcode复习: 堆和栈
    leetcode 的shell部分4道题整理
    Regular Expression Matching [leetcode]
    深入浅出JAVA
  • 原文地址:https://www.cnblogs.com/jinshao/p/15009026.html
Copyright © 2020-2023  润新知