laravel5.2 學習之服務提供者

契約接口:app\Contracts\LanguageContract.phpphp

<?php
namespace App\Contracts;

interface LanguageContract {
    public function speaking();
}

服務類:app\Services\ChineseService.php數組

<?php
namespace App\Services;
use App\Contracts\LanguageContract;

class ChineseService implements LanguageContract {
    public function speaking() {
        return '你說的是中文哦';
    }
}

服務類:app\Services\EnglishService.phpapp

<?php
namespace App\Services;
use App\Contracts\LanguageContract;

class EnglishService implements LanguageContract {
    public function speaking() {
        return 'You are speaking English';
    }
}

服務提供者:app\Providers\TestServiceProvider.phpide

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register() {
        //綁定接口到容器
        $this->app->bind('App\Contracts\LanguageContract', 'App\Services\ChineseService');

        /**
        //綁定類名到單例---返回中文--測試可行
        $this->app->singleton('chinese', function () {
        //須要 use App\Services\ChineseService;
        //控制器中 App::make('chinese') 返回對象
        return new ChineseService();
        });
         */
        /**
        //綁定類名到單例---測試可行,不須要引入服務類了
        $this->app->singleton('chinese', function () {
        return new \App\Services\ChineseService();
        });
         */
        /**
        //普通綁定類名----測試可行
        $this->app->bind('chinese', function () {
        return new \App\Services\ChineseService();
        });
         */

        /**
        //綁定類到單例---返回英文---測試可行
        $this->app->singleton('english', function () {
        // use App\Services\EnglishService;
        //控制器中 App::make('english') 返回對象
        return new EnglishService();
        });
         */

    }
}

而後在config\app.php中的providers數組中註冊該服務測試

控制器測試this

public function c1() {
        //$test = App::make('chinese');
        $test1 = App::make('App\Contracts\LanguageContract');
        //$test2 = App::make('english');
        var_dump($test1->speaking());
        //var_dump($test2->speaking());
    }
相關文章
相關標籤/搜索