欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Laravel 框架核心:服务容器与门面模式

时间:2026年08月12日 04:46:50 浏览:0

服务容器(Service Container)


Laravel 的服务容器是 IoC(控制反转)容器,负责类的依赖解析。


绑定


// 在 AppServiceProvider 中
use App\Services\PaymentService;
use App\Contracts\PaymentInterface;

$this->app->bind(PaymentInterface::class, PaymentService::class);

// 单例绑定
$this->app->singleton(SomeService::class, function ($app) {
return new SomeService($app->make(Config::class));
});

解析


// 方式一:app() 辅助函数
$service = app(PaymentInterface::class);

// 方式二:依赖注入(控制器/构造函数)
public function __construct(private PaymentInterface $payment) {}

// 方式三:服务定位器
$service = resolve(PaymentInterface::class);

门面(Facade)


门面提供静态风格的接口,实际调用底层服务。


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

// 门面调用
Cache::put('key', 'value', 60);
$users = DB::table('users')->get();

自定义门面


use Illuminate\Support\Facades\Facade;

class MyServiceFacade extends Facade {
protected static function getFacadeAccessor() {
return 'my-service'; // 需在容器中注册
}
}

理解服务容器和门面,是掌握 Laravel 精髓的关键一步。