Laravel中服务提供者到容器的使用是一个非常核心的概念应用, 给一个实际应用实例方便大家理解学习
实例过程简介:
1. 定义接口名称 GobjContract [去北京]
2. 实现接口的两个方法 WalkbjService [步行去北京], TrainbjService[搭火车去北京], 当然, 还可以有好多种实现了
3. 服务提供者注册, 注册去北京的方法, 注册哪个方法, 在应用中 依赖注入时, 就会使用哪种方法[这个是 服务提供者的 主要用途]
注意: 如果是单独的一个实例, 没有应用 契约[PHP接口], 就没有必要使用服务提供者了[Laravel本身支持自动加载注入]
实现步骤如下:
第一步: 定义去北京的接口
namespace App\Contracts;
//去北京的接口
interface GobjContract
{
public function howTo();
}
第二步:定义实现去北京的方法:
1>
namespace App\Services;
use App\Contracts\GobjContract;
//步行去北京
class WalkbjService implements GobjContract
{
public function howTo(){
echo "我要步行去北京";
}
}
2>
namespace App\Services;
use App\Contracts\GobjContract;
//步行去北京
class TrainbjService implements GobjContract
{
public function howTo(){
echo "我要乘火车去北京";
}
}
第三步: 实现服务提供者 php artisan make:provider GobjServiceProvidernamespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\WalkbjService;
use App\Services\TrainbjService;
class GobjServiceProvider 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\GobjContract',function(){
return new WalkbjService();
});
//绑定去北京的方法为乘火车
/*$this->app->bind('App\Contracts\GobjContract',function(){
return new TrainbjService();
});*/
}
}
第四步:注册服务提供者到容器 App\Providers\GobjServiceProvider::class
第五步:配置路由: Route::resource('gobj','GobjController');
第六步: 创建控制器: php artisan make:controller GobjController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App;
use App\Contracts\GobjContract;
class GobjController extends Controller
{
//
protected $gobj;
public function __construct(GobjContract $gobj)
{
$this -> gobj = $gobj;
}
public function index()
{
$this -> gobj -> howTo();
//服务提供者绑定步行: 这里输出结果为步行
//服务提供者绑定乘火车:这里输出结果为 乘火车
}
}
现在可以通过浏览器进行访问了:http://laravel.cn/gobj
