Booting Providers 服务提供者的启动过程

After all providers have been registered, they are "booted". This will fire the boot method on each provider. A common mistake when using service providers is attempting to use the services provided by another provider in the register method. Since, within the register method, we have no gurantee all other providers have been loaded, the service you are trying to use may not be available yet. So, service provider code that uses other services should always live in the boot method. The register method should only be used for, you guessed it, registering services with the container.

在所有服务提供者都注册以后,他们就进入了“启动”过程。该过程会触发每个服务提供者的 boot 方法。这里会发生一种常见的错误用法:在 register 方法里面调用其他的服务。由于在 register 方法里我们不能保证所有其他服务都已经被加载,所以在该方法里调用别的服务有可能会出错。所以如果你想在服务提供者里调用别的服务,请在 boot 方法里做这种事儿。register 方法只能进行容器注册。

Within the boot method, you may do whatever you like: register event listeners, include a route file, register filters, or anything else you can imagine. Again, use the provider as organizational tools. Perhaps you wish to group some related event listeners together? Placing them in the boot method of a service provider would be a great approach! Or, you could include an "events" or "routes" PHP file:

在启动方法里面,你想做什么都可以:注册事件监听,引入路由文件,注册过滤器,或者其他你能想象到的事儿。再强调一下,要发挥服务提供者的管理功能。可能你想将相关的多个事件监听归为一组?将他们放到一个服务提供者的 boot 方法里,这会很管用的!或者你也可以引入单独的 “events”、“routes” PHP文件:

public function boot()
    require_once __DIR__.'/events.php';
    require_once __DIR__.'/routes.php';

Now that we've learned about dependency injection and a way to organize our projects around providers, we have a great foundation for building well-architected Laravel applications that are maintainable and testable. Next, we'll explore how Laravel itself uses providers, and how the framework works under the hood!

我们已经学习了依赖注入以及如何使用服务提供者来组织管理我们的项目。这样我们的 Laravel 应用就有了一个很好的基础,它结构优美并且易于维护和测试。接下来,我们将探索 Laravel 框架本身是如何使用服务提供者的,并且深究其原理!

Don't Box Yourself In 不要让条条框框限制你自己

Remember, don't assume that service providers are something that only packages use. Create your own to help organize your application's services.

记住,服务提供者不仅仅是专业的软件包才能使用。 请大胆的使用它来组织管理你的应用服务吧。

results matching ""

    No results matching ""