laravel5.2 学习之服务提供者

时间:2024-07-05 09:34:08

契约接口:app\Contracts\LanguageContract.php

<?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.php

<?php
namespace App\Services;
use App\Contracts\LanguageContract; class EnglishService implements LanguageContract {
public function speaking() {
return 'You are speaking English';
}
}

服务提供者:app\Providers\TestServiceProvider.php

<?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数组中注册该服务

控制器测试

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());
}