服务提供者

更新时间: 2019-08-01 16:47

简介

服务提供者是所有 Lumen 应用程序启动的中心所在。包括你自己的应用程序,以及所有的 Lumen 核心服务,都是通过服务提供者启动的。

但是,我们所说的「启动」指的是什么?一般而言,我们指的是注册事物,包括注册服务容器绑定、事件侦听器、中间件,甚至路由。服务提供者是设置你的应用程序的中心所在。

若你打开 Lumen 的 bootstrap/app.php 文件,你将会看到 $app->register()方法的调用。你也许需要额外的调用来注册你的服务提供者。

编写服务提供者

所有的服务提供者都继承了 Illuminate\Support\ServiceProvider 这个类。这个抽象类要求你在你的提供者上定义至少一个方法:register。在 register 方法内,你应该 只需要将事物绑定到服务容器中。永远不要试图在 register 方法中注册任何事件侦听器、路由或任何其它功能。

注册方法

如前面所讲,在 register 方法中,你只要将事物绑定到「服务容器中」。永远不要试图在 register 方法中注册任何事件侦听器、路由或任何其它功能。否则,你有可能会意外的使用到尚未加载的服务提供者提供的服务。

现在,让我们来看一个基本的服务提供者的代码:

<?php

namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider
{
    /**
     * 注册绑定到容器中
     *
     * @return  void
     */
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection(config('riak'));
        });
    }
}

这个服务提供者只定义了一个 register 方法,并且用这个方法在服务容器中绑定了 Riak\Connection 的一个实例。如果你不是很了解服务容器的运行原理,请查看 「its documentation」。

启动方法

那么,如果我们要在服务提供者当中注册一个视图组件呢?这应该在 boot 方法内完成。 此方法在所有其他服务提供者都注册之后才能调用,也就意味着可以访问已经被框架注册的所有服务:

<?php

namespace App\Providers;

use Queue;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // 其他服务提供者属性 ...

    /**
     * 引导任何应用程序服务。
     *
     * @return  void
     */
    public function boot()
    {
        Queue::failing(function ($event) {

        });
    }
}

注册服务提供者

所有的服务提供者在 bootstrap/app.php 文件中被注册。这个文件中包含对 $app->register() 方法调用。你也行需要额外的调用 $app->register() 来注册你的服务提供者。

查看更多 Laravel 中文文档 信息

Refactoring

Refactoring

Martin Fowler、Kent Beck、John Brant、William Opdyke、Don Roberts / Addison-Wesley Professional / 1999-7-8 / USD 64.99

Refactoring is about improving the design of existing code. It is the process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its int......一起来看看 《Refactoring》 这本书的介绍吧!

RGB转16进制工具

RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换

RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具

HEX CMYK 转换工具

HEX CMYK 互转工具