iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
2
Software Development

PHP新手30天實戰金流系列 第 7

[Day7] Laravel 架構理解( IoC, Service Provider)

tags: PHP新手30天實戰金流, Laravel6

IoC Container

  1. IoC 全名 Inversion Of Control,控制翻轉
  2. 核心概念:簡單來說就是 class 內部不會用 new 的方式去實例化依賴的服務, 而是由外部 interface 通過 Dependency Injection(依賴注入)的方式獲取實例。
  3. 我們專案中的 $app 就是一個 IoC container,定義在bootstrap/app.php
<?php
/*
| Create The Application
*/

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

/*
| Bind Important Interfaces
*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

return $app;

  1. Container 只有兩個步驟 bind & make:
    • pseudo code :
    <?php
    $containter = require('Container');
    
    // 建立抽象與實體類別的對應
    $containter->bind(ILogService, AWSLogServcie::class);
    
    $log = $container->make(Log::class);
    
    $log->send('log....'); 
    
    • bind
      1. 註冊:建立抽象與實體類別的綁定表。將 Interface 和實現他的 class 綁定
      2. 有四種方式:
        1. 類別綁定 clouse
        App::bind('UserRepository', function()
        {
            return new AWSUserRepository;
        });
        
        1. 抽像類別綁定實際類別
        App::bind('UserRepositoryInterface', 'DbUserRepository');
        
        1. 實際類別綁定
        APP::bind('UserRepository')
        
        1. singleton 綁定
        App::singleton('UserRepository', function()
        {
            return new AWSUserRepository;
        });
        
    • make
      • 使用方法
      <?php
      
      $app->make('UserRepository');
      
      • 用途:實例化。(用 interface 名,非 class 名)其執行順序為:
        1. resolve 解析
        2. 解析後若沒有其他依賴,則 build。若還有依賴,遞回 call make,繼續解析依賴

Service Provider

  1. 核心概念:註冊與管理 Container 內服務的地方。會根據模組來產生不同的 Provider。
  2. Provider 有兩個步驟:register & boot
    • register
      • 用來寫 bind,負責綁定service到container
      • 只需要將事物綁定到服務容器。而不要嘗試在register方法中註冊任何監聽器
    • boot
      • register 結束後執行的方法。使用這個 service 的前處理

Why 要有 Provider?

  • 若都在同一支 bootstrap/app.php 註冊,多人開發時,會一直有 merge conflict

  • 實際執行 service proivder 的方法在 ProviderRepository 中。主要流程如下:

    1. 讀取 boostrap/cache/services.php。
    2. 判斷是否重新產生 cache 檔。
    3. 從 cache 檔中判斷每個 servcie provider 是那一類型,然後分別執行。
    • 基本上 cache 檔中 service provider 被分為三種類別,它們的特點如下 :
      1. when : 當某個事件被執行的時後,才會執行 service provider。
      2. eager : 直接執行 service provider。
      3. deferred : 等到要執行 make 前,才會執行 service provider。

資料來源:

  1. 參考大神 :PHP Laravel 的 Service Provider 理解

阿... 還有好多不懂的地方..內容會再追加補充><

晚生學習分享所學經驗,若內容有誤或不清楚,煩請不吝指教!更是歡迎各位大神多多補充,感謝萬分!


上一篇
[Day6] Shopping Cart - Views - Controller - DB
下一篇
[Day8] 金流是什麼
系列文
PHP新手30天實戰金流34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言