一、手动创建服务
1.创建服务
interface Food
{
public function weight();
}
class Apple implements Food
{
public $weight;
public function __construct($weight)
{
$this->weight = $weight;
}
public function weight()
{
return $this->weight;
}
}
2.绑定服务
app()->bind('yuan', function () {
return new Apple(18);
});
Route::get('d1', function () {
dd(resolve('yuan'));
});
app()->bind('Food', 'Apple');
app()->when('Apple')->needs('$weight')->give('100');
Route::get('d1',function (){
dd(app('Food'));
});
二、Laravel服务创建
3.Laravel创建服务
php artisan make:provider DemoServiceProvider
4.注册服务
'providers' => [
App\Providers\DemoServiceProvider::class
],
5.绑定服务
public function register()
{
$this->app->bind('Demo', function () {
return 'Demo';
});
}
Route::get('d2',function (){
dd(resolve('Demo'));
});
三、Laravel中使用
6.创建接口和实现类
namespace App\Http\Controllers;
interface Food
{
public function weight();
}
namespace App\Http\Controllers;
class Apple implements Food
{
public $weight;
public function __construct($weight)
{
$this->weight = $weight;
}
public function weight()
{
return $this->weight();
}
}
7.绑定服务
$this->app->bind('Food', 'Apple');
$this->app->when('Apple')->needs('$weight')->give('0101');
Route::get('d2',function (){
dd(app('Food'));
});
Target class [Apple] does not exist
$this->app->bind('Food', function () {
return new Apple(18);
});
$weight = 15;
$this->app->singleton('Food', function ($app) use ($weight) {
return new Apple($weight);
});
8.服务懒加载
class DemoServiceProvider extends ServiceProvider implements DeferrableProvider
{
public function provides()
{
return [Food::class];
}
}