[英]Laravel Service Container and Service Provider
需要通過一個例子來了解 Laravel 服務容器和服務提供者。
您好,歡迎來到 stackoverflow!
服務容器是存儲我們的應用程序bindings
的地方。 服務提供者是我們將綁定注冊到服務容器的類。 在舊版本的 Laravel 中,我們沒有這些提供者,人們總是問在哪里放置綁定。 答案令人困惑。 “最有意義的地方。”! 然后,Laravel 引入了這些服務提供者和提供者目錄,以便為人們清理。
為了便於理解,我將包含一個基本示例:
interface AcmeInterface {
public function sayHi();
}
class AcmeImplementation implements AcmeInterface {
public function sayHi() {
echo 'Hi!';
}
}
// Service Container
$app = new \Illuminate\Database\Container;
// Some required stuff that are also service providing lines
// for app config and app itself.
$app->singleton('app', 'Illuminate\Container\Container');
$app->singleton('config', 'Illuminate\Config\Repository');
// Our Example Service Provider
$app->bind(AcmeInterface::class, AcmeImplementation::class);
// Example Usage:
$implementation = $app->make(AcmeInterface::class);
$implementation->sayHi();
正如你看到的;
bootstrap/app.php
為我們做這件事),config/app.php
),服務容器是您注冊服務的地方。
服務提供者通過將服務添加到容器中來提供服務。
參考Laracast 。 注意了解。
服務容器: https : //laracasts.com/series/laravel-from-scratch-2017/episodes/24
服務提供商: https : //laracasts.com/series/laravel-from-scratch-2017/episodes/25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.