1. 程式人生 > 實用技巧 >Laravel核心思想

Laravel核心思想

服務容器

Laravel 中的容器

  • 繫結 由 服務提供者進行
$this->app->bind('HelpSpot\Api', function($app){
    return new HelpSpot\API($app->make('HttpClient'));
});

$this->app->singleton('HelpSpot\Api', function($app){
    return new HelpSpot\API($app->make('HttpClient'));
});
 
  • 解析
$api = $this->app->make('HelpSpot\Api');

IOC控制反轉

DI依賴注入

設計思想,Laravel中使用反射來進行

服務提供者

  • 服務註冊
    public function register() 在所有服務提供者提供服務前註冊
    public function boot() 在所有服務提供者載入後

  • 延遲服務提供 protected $defer = true; 第一次使用時才進行載入

門臉模式

dd(\Request::all()); // 對應 app/config.php aliases 中定義的門臉類 'Request' => Illuminate\Support\Facades\Request::class,

class Request extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'request';      // 返回服務註冊名
    }
}

關聯

    // 容器中獲取 Log 例項
    public function index()
    {
        $app = app();       // 獲取容器

        /*
         'log' 字串為註冊在服務容器的識別符號
          Application.php 中 `public function registerBaseServiceProviders` 的 
          `$this->register(new LogServiceProvider($this));` 進行註冊
         */
        $logger = $app->make("log");

        $logger->info("post_index", ['data' => 'this is post index']);
    }
    // 依賴注入的方式
    // Application.php 中的 `public function registerCoreContainerAliases()` 定義了別名
    // 'log'  => [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class],
    public function index1(\Psr\Log\LoggerInterface $logger)
    {
        $logger->info("post_index", ['data' => 'this is post index']);
    }
    // 門臉方式
    // config/app.php 中定義了 'Log' => Illuminate\Support\Facades\Log::class,
    public function index2()
    {
        \Log::info("post_index", ['data' => 'this is post index']);
    }