目錄
What is the Service Container?
1. Understanding Dependency Injection
Example Without Injection
With Constructor Injection
2. How Laravel Resolves Dependencies
3. Binding Interfaces to Implementations
Example:
4. Contextual Bindings
5. Singleton Bindings
6. Binding Primitives (Scalar Values)
7. Using Dependency Injection in Different Contexts
In Controllers
In Middleware
In Jobs, Listeners, and Commands
8. Service Providers: Where Bindings Live
9. Resolving Instances Manually
Summary of Key Points
首頁 php框架 Laravel 如何在Laravel中使用服務容器和依賴注入?

如何在Laravel中使用服務容器和依賴注入?

Aug 02, 2025 pm 01:43 PM

Laravel的依賴注入與服務容器通過自動解析類型提示的依賴實現解耦,1. 使用構造函數注入將依賴外部化;2. 在服務提供者中通過bind綁定接口到具體實現;3. 使用singleton確保單例;4. 通過needs()->give()注入標量值;5. 利用when()->needs()->give()實現上下文綁定;6. 在控制器、中間件、任務等中直接類型提示依賴;7. 可使用app()或resolve()手動解析實例,最終實現靈活、可測試的應用架構。

How to use service containers and dependency injection in Laravel?

In Laravel, service containers and dependency injection are core concepts that help you build flexible, testable, and maintainable applications. Let's break down how to use them effectively.

How to use service containers and dependency injection in Laravel?

What is the Service Container?

The service container is Laravel's powerful inversion of control (IoC) container. It manages class dependencies and automatically resolves them when needed. This means you don't have to manually create objects — Laravel does it for you.


1. Understanding Dependency Injection

Dependency injection is a design pattern where a class receives its dependencies from the outside, rather than creating them internally.

How to use service containers and dependency injection in Laravel?

Example Without Injection

 class OrderController extends Controller
{
    public function store()
    {
        $logger = new FileLogger(); // Hardcoded dependency
        $logger->log('Order created');
    }
}

This is inflexible — you can't easily switch loggers.

With Constructor Injection

 class OrderController extends Controller
{
    protected $logger;

    public function __construct(FileLogger $logger)
    {
        $this->logger = $logger;
    }

    public function store()
    {
        $this->logger->log('Order created');
    }
}

Now, the controller doesn't care how FileLogger is built — the container handles it.

How to use service containers and dependency injection in Laravel?

2. How Laravel Resolves Dependencies

When Laravel sees a type-hinted class in a constructor or method, it tries to resolve it from the container.

 public function __construct(UserRepository $repo)
{
    $this->repo = $repo;
}

If UserRepository has its own dependencies (eg User model, Cache ), Laravel recursively resolves them — as long as they're type-hinted.


3. Binding Interfaces to Implementations

This is where the container shines. You can bind an interface to a concrete class, allowing easy swapping.

Example:

 // In a service provider (like AppServiceProvider)
public function register()
{
    $this->app->bind(
        PaymentGatewayInterface::class,
        StripePaymentGateway::class
    );
}

Now, anywhere you type-hint PaymentGatewayInterface , Laravel injects StripePaymentGateway .

 public function pay(PaymentGatewayInterface $gateway)
{
    $gateway->charge(100);
}

You can later change the binding to PayPalPaymentGateway without touching the controller.


4. Contextual Bindings

Sometimes you want different implementations based on the consumer.

 $this->app->when(InvoiceController::class)
          ->needs(PaymentGatewayInterface::class)
          ->give(StripePaymentGateway::class);

$this->app->when(ReceiptController::class)
          ->needs(PaymentGatewayInterface::class)
          ->give(PayPalPaymentGateway::class);

5. Singleton Bindings

Use singleton() if you want the same instance returned every time:

 $this->app->singleton(ReportGenerator::class, function ($app) {
    return new ReportGenerator();
});

Now, every time ReportGenerator is resolved, the same instance is used.


6. Binding Primitives (Scalar Values)

You can inject configuration values or strings using contextual binding:

 $this->app->when(StripePaymentGateway::class)
          ->needs('$apiKey')
          ->give(config('services.stripe.key'));

Then in your class:

 class StripePaymentGateway
{
    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
    }
}

7. Using Dependency Injection in Different Contexts

In Controllers

Laravel automatically resolves type-hinted dependencies in controller constructors or methods.

 public function index(UserRepository $users)
{
    return $users->all();
}

In Middleware

 public function handle($request, Closure $next, UserService $service)
{
    // $service is auto-injected
    return $next($request);
}

In Jobs, Listeners, and Commands

Same rules apply — type-hint dependencies in the constructor.


8. Service Providers: Where Bindings Live

Create custom service providers to organize your bindings:

 php artisan make:provider PaymentServiceProvider

Then register it in config/app.php or use Laravel 5.5 auto-discovery.

 // PaymentServiceProvider.php
public function register()
{
    $this->app->bind(PaymentProcessor::class, function ($app) {
        return new PaymentProcessor(
            config('services.payment.secret')
        );
    });
}

9. Resolving Instances Manually

You can pull instances from the container using app() or resolve() :

 $logger = app()->make(LoggerInterface::class);
// or
$logger = resolve(LoggerInterface::class);

Even simpler:

 $logger = app(LoggerInterface::class);

Summary of Key Points

  • Laravel's service container automatically resolves dependencies via type hints.
  • Use bind() to map interfaces to implementations.
  • Use singleton() for single instance sharing.
  • Inject scalar values with needs()->give() .
  • Define bindings in service providers.
  • Dependency injection works in controllers, middleware, jobs, and more.

Basically, just type-hint your dependencies — Laravel handles the rest, as long as things are properly bound. It keeps your code decoupled and easier to test.

以上是如何在Laravel中使用服務容器和依賴注入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey如何釣魚
1 個月前 By Jack chen
Kimi K2:最強大的開源代理模型
1 個月前 By Jack chen
我可以有兩個支付帳戶嗎?
1 個月前 By 下次还敢

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1602
29
PHP教程
1506
276
選擇API身份驗證的Laravel Sanctum和Passport 選擇API身份驗證的Laravel Sanctum和Passport Jul 14, 2025 am 02:35 AM

LaravelSanctum適合簡單、輕量的API認證,如SPA或移動應用,而Passport適用於需要完整OAuth2功能的場景。 1.Sanctum提供基於令牌的認證,適合第一方客戶端;2.Passport支持授權碼、客戶端憑證等複雜流程,適合第三方開發者接入;3.Sanctum安裝配置更簡單,維護成本低;4.Passport功能全面但配置複雜,適合需要精細權限控制的平台。選擇時應根據項目需求判斷是否需要OAuth2特性。

管理數據庫狀態進行Laravel測試 管理數據庫狀態進行Laravel測試 Jul 13, 2025 am 03:08 AM

在Laravel測試中管理數據庫狀態的方法包括使用RefreshDatabase、選擇性播種數據、謹慎使用事務和必要時手動清理。 1.使用RefreshDatabasetrait自動遷移數據庫結構,確保每次測試都基於乾淨的數據庫;2.通過調用特定種子填充必要數據,結合模型工廠生成動態數據;3.使用DatabaseTransactionstrait回滾測試更改,但需注意其局限性;4.在無法自動清理時,手動截斷表或重新播種數據庫。這些方法根據測試類型和環境靈活選用,以保證測試的可靠性和效率。

處理Laravel中的HTTP請求和響應。 處理Laravel中的HTTP請求和響應。 Jul 16, 2025 am 03:21 AM

在Laravel中處理HTTP請求和響應的核心在於掌握請求數據獲取、響應返回和文件上傳。 1.接收請求數據可通過類型提示注入Request實例並使用input()或魔術方法獲取字段,結合validate()或表單請求類進行驗證;2.返迴響應支持字符串、視圖、JSON、帶狀態碼和頭部的響應及重定向操作;3.處理文件上傳時需使用file()方法並結合store()存儲文件,上傳前應驗證文件類型和大小,存儲路徑可保存至數據庫。

在Laravel生成命名路線的URL。 在Laravel生成命名路線的URL。 Jul 16, 2025 am 02:50 AM

在Laravel中生成命名路由的URL最常用方法是使用route()輔助函數,它可根據路由名稱自動匹配路徑並處理參數綁定。 1.在控制器或視圖中傳入路由名稱和參數,如route('user.profile',['id'=>1]);2.多參數時也只需傳數組,順序不影響匹配,如route('user.post.show',['id'=>1,'postId'=>10]);3.在Blade模板中可直接嵌入鏈接,如查看資料;4.可選參數未提供時不顯示,如route('user.post',

Laravel中的配置緩存是什麼? Laravel中的配置緩存是什麼? Jul 27, 2025 am 03:54 AM

Laravel的配置緩存通過合併所有配置文件為一個緩存文件來提升性能。在生產環境中啟用配置緩存可減少每次請求時的I/O操作和文件解析,從而加快配置加載速度;1.應在部署應用、配置穩定且無需頻繁更改時啟用;2.啟用後修改配置需重新運行phpartisanconfig:cache才會生效;3.避免在配置文件中使用依賴運行時條件的動態邏輯或閉包;4.排查問題時應先清除緩存、檢查.env變量並重新緩存。

如何在Laravel執行請求驗證? 如何在Laravel執行請求驗證? Jul 16, 2025 am 03:03 AM

在Laravel中進行請求驗證有兩種主要方法:控制器驗證和表單請求類。 1.控制器中使用validate()方法適合簡單場景,直接傳入規則並自動返回錯誤;2.使用FormRequest類適用於復雜或複用場景,通過Artisan創建類並在rules()中定義規則,實現代碼解耦與復用;3.可通過messages()自定義錯誤提示,提升用戶體驗;4.通過attributes()定義字段別名,使錯誤信息更友好;兩種方式各有優劣,應根據項目需求選擇合適方案。

解釋Laravel雄辯的範圍。 解釋Laravel雄辯的範圍。 Jul 26, 2025 am 07:22 AM

Laravel的EloquentScopes是封裝常用查詢邏輯的工具,分為本地作用域和全局作用域。 1.本地作用域以scope開頭的方法定義,需顯式調用,如Post::published();2.全局作用域自動應用於所有查詢,常用於軟刪除或多租戶系統,需實現Scope接口並在模型中註冊;3.作用域可帶參數,如按年份或月份篩選文章,調用時傳入對應參數;4.使用時注意命名規範、鍊式調用、臨時禁用及組合擴展,提升代碼清晰度與復用性。

使用翻譯員立面在Laravel中進行定位。 使用翻譯員立面在Laravel中進行定位。 Jul 21, 2025 am 01:06 AM

thetranslatorfacadeinlaravelisused forlocalization byfetchingTranslatingStringSandSwitchingLanguagesAtruntime.Touseit,storetranslationslationstringsinlanguagefilesunderthelangderthelangdirectory(例如,ES,ES,FR),thenretreiveTreivEthemvialang :: thenretRievEtheMvialang :: get()

See all articles