场景
- 这几天看了文档, 有些简单的理解
文档
- 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;
}
}