服务提供器
- 服务提供者是
Laravel应用启动引导中心
作用
- 将类、接口绑定到服务容器(依赖注入)
- 注册事件、视图合成器、宏、命令、路由、资源(配置 / 视图 / 语言包)
- 第三方扩展包与
Laravel框架的接入点
register()
- 执行时机:最先执行,所有
Provider逐个执行register方法 - 职责:只做容器绑定(bind / singleton)
- 禁止:不要在这里
$this->app->make()。原因:此时其他服务可能还没注册,解析会报错。
register 只做绑定
boot()
- 执行时机:所有
Provider的register方法执行完毕后,逐个执行boot方法 - 职责:解析容器服务、注册事件监听、视图合成器、宏、模型观察者、加载路由等
boot 做一切初始化业务。
实战
先创建业务类 & 接口
php
// app/Contracts/PaymentInterface.php
namespace App\Contracts;
interface PaymentInterface
{
public function pay(int $amount): string;
}php
// app/Services/AlipayService.php
namespace App\Services;
use App\Contracts\PaymentInterface;
class AlipayService implements PaymentInterface
{
public function pay(int $amount): string
{
return "支付宝支付:{$amount}元";
}
}编写服务提供者
php
// app/Providers/PaymentServiceProvider.php
namespace App\Providers;
use App\Contracts\PaymentInterface;
use App\Services\AlipayService;
use Illuminate\Support\ServiceProvider;
class PaymentServiceProvider extends ServiceProvider
{
/**
* 容器绑定(仅绑定,不要解析服务)
*/
public function register(): void
{
// 方式1:绑定接口 → 实现类(每次make新建实例)
$this->app->bind(PaymentInterface::class, AlipayService::class);
// 方式2:单例 singleton(全局只创建一次)
// $this->app->singleton(PaymentInterface::class, AlipayService::class);
// 方式3:闭包绑定(需要构造参数时使用)
/*
$this->app->singleton(PaymentInterface::class, function($app){
return new AlipayService();
});
*/
}
/**
* 所有服务注册完成后启动业务逻辑
*/
public function boot(): void
{
// 示例1:注册模型观察者
// User::observe(UserObserver::class);
// 示例2:Response 宏
/*
response()->macro('success', function($data){
return response()->json(['code'=>200,'data'=>$data]);
});
*/
// 示例3:boot 支持依赖注入
/*
public function boot(\Illuminate\Contracts\Cache\Repository $cache)
{
$cache->get('xxx');
}
*/
}
}使用(依赖注入)
php
use App\Contracts\PaymentInterface;
public function index(PaymentInterface $payment)
{
echo $payment->pay(100);
}