search
HomeBackend DevelopmentPHP Tutoriallaravel 基础教程 -- 服务提供者

简介

服务提供者是 laravel 应用启动的中心。你自己的应用以及 laravel 的核心服务都是通过服务提供者来启动的。

但是,我们所指的启动是什么意思?通常情况下,这意味着注册,包含注册服务的绑定,事件监听,中间件,和路由。服务提供者是应用配置的中心。

如果你打开 config/app.php 文件,你会发现 providers 数组。这些都是你的应用将要加载的服务提供者类。当然,很多是延迟加载的提供者,意思就是并不是所有的请求都会加载这些提供者,而是只有需要的时候才会加载。

在此篇,你将学会如果去编写自己的服务提供者并且将其注册到应用中。

编写服务提供者

所有的服务提供者都继承自 Illuminate\Support\ServiceProvider 类。这个抽象类要求你的提供者必须最少定义一个 register 方法。在 register 方法中你应该只绑定内容到服务容器。你永远不要尝试在其中注册任何的事件监听,路由或者其它功能。

Artisan CLI 可以通过 make:provider 命令来非常便捷的生成一个新的提供者:

php artisan make:provider RiakServiceProvider

注册方法

就如前面所提到的,在 register 方法中,你应该只做一件事,那就是绑定事物到服务容器中。不要做其它的事情。否则,可能你所使用的提供者提供的服务还没有被注册。现在,让我们来看一个最基础的服务提供者:

<?phpnamespace App\Providers;use Riak\Connection;use Illuminate\Support\ServiceProvider;class RiakServiceProvider extends ServiceProvider{  /**   * Register bindings in the container.   *   * @return void   */   public function register()   {     $this->app->singleton(Connection::class, function ($app) {         return new Connection(config('riak'));     });   }}

这个服务提供者仅仅只定义了一个 register 方法,并且使用这个方法在服务容器中定义了一个 Riak\Connection 的实现。如果你并不理解服务容器是如何工作的,你可以看一下服务容器的文档。

启动方法

如果我们想在服务提供者中注册一个视图 composer,那么我们应该在 boot 方法中做这些。boot 方法会在所有的服务提供者都注册完成之后才会被执行。这意味着你有访问所有服务的权限:

<?phpnamespace App\Providers;use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;class EventServiceProvider extends ServiceProvider{  // Other Service Provider Properties...  /**   * Register any other events for your application.   *   * @param \Illuminate\Contracts\Events\Dispatcher $events   * @return void   */   public function boot(DispatcherContract $events)   {     parent::boot($events);     view()->composer('view', function () {       //     });   }}

启动方法的依赖注入

你可以在服务提供者的 boot 方法中使用类型提示来标识依赖。服务容器将会自动的将所需要的依赖注入进去:

use Illuminate\Contracts\Routing\ResponseFactory;public function boot(ResponseFactory $factory){  $factory->macro('caps', function ($value)){    //  };}

注册提供者

所有的服务提供者都被注册在 config/app.php 配置文件中。这个文件包含了 providers 数组,这数组列出了所有服务提供者的名字。默认的,laravel 中的核心服务都被注册在这个数组里。这些提供者启动了 laravel 中的核心组件,如邮件,队列,缓存和其他。

你可以在该数组中进行添加注册提供者:

'providers' => [  // Other Service Providers  App\Providers\AppServiceProvider::class,],

延迟加载提供者

如果你的提供者只是在服务容器中注册一些绑定信息,那么你可以选择推迟注册,这样这些服务只有在真正被需要用到时才会进行注册。推迟注册能够提高你的应用的性能。因为它不会在所有请求到来时都通过文件系统来加载。

为了推迟提供者的加载,你可以在提供者类中设置 defer 属性为 true 并且定义一个 provides 方法。provides 方法会返回提供者注册的服务容器的绑定:

<?phpnamespace App\Providers;use Riak\Connection;use Illuminate\Support\ServiceProvider;class RiakServiceProvider extends ServiceProvider{  /**   * Indicates if loading of the provider is deferred.   *   * @var bool   */   protected $defer = true;   /**    * Register the service provider.    *    * @return void    */    public function register()    {      $this->app-singleton(Connection::class, function ($app) {        return new Connection($app['config']['riak']);      });    }    /**     * Get the services provided by the provider.     *     * @return array     */     public function provides()     {        return [Connection::class];     }}

laravel 会编译和存储所有延迟加载的服务提供者的服务列表及服务提供者的类名。然后,只有当你尝试解析其中的某个服务时,laravel 才会加载其服务提供者。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment