天天看點

laravel 談談對service container service provider facade contract的簡單了解

文章目錄

      • 場景
      • 文檔
      • 簡單了解

場景

  • 這幾天看了文檔, 有些簡單的了解

文檔

  • laravel service container文檔
  • laravek service provider文檔
  • laravel facade文檔
  • laravel contract 文檔

簡單了解

  • service container
    • The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection

    • service container 就是管理和執行依賴注入的工具。簡單的了解成服務容器内部的key指向的是serive provider.
  • service provider
    • Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers But, what do we mean by "bootstrapped"? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

    • 服務都是通過servicer provider 注冊在service container 中的
    • 場景的服務都在config/app.php
  • facade
    • Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features. Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

    • facade 是service的靜态代理, 可以靜态的方式調用servie container對應的方法
    • VS 依賴注入

      依賴注入一般是可以通過__construct 檢視注入的數量, Facade 則不好控制引入的數量
  • contracts
  • Laravel's Contracts are a set of interfaces that define the core services provided by the framework。Each contract has a corresponding implementation provided by the framework.

  • contracts是一組接口,定義了servier 需要實作的功能。 本質上和facade沒有差別

    具體使用那個需要看個人喜好。

  • 使用contacts可以有效的降低耦合
  • 官網中有個有趣的列子
高度耦合
<?php

namespace App\Orders;

class Repository
{
    /**
     * The cache instance.
     */
    protected $cache;

    /**
     * Create a new repository instance.
     *
     * @param  \SomePackage\Cache\Memcached  $cache
     * @return void
     */
    public function __construct(\SomePackage\Cache\Memcached $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Retrieve an Order by ID.
     *
     * @param  int  $id
     * @return Order
     */
    public function find($id)
    {
        if ($this->cache->has($id))    {
            //
        }
    }
}


           
contract 降低耦合
<?php

namespace App\Orders;

use Illuminate\Contracts\Cache\Repository as Cache;

class Repository
{
    /**
     * The cache instance.
     */
    protected $cache;

    /**
     * Create a new repository instance.
     *
     * @param  Cache  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }
}