Home >PHP Framework >Laravel >Get the container instance in the code (Laravel)

Get the container instance in the code (Laravel)

藏色散人
藏色散人forward
2021-08-06 09:35:101893browse

This article is written by the tutorial column of laravel to introduce how to obtain the container instance in the code. I hope it will be helpful to friends in need!

The laravel container instance is unique throughout the request life cycle and manages all service component instances. So what are the ways to get an instance of the laravel container? The following methods are commonly used:

1) Through the help function of app:

$app = app();

The auxiliary function of app is defined in

Get the container instance in the code (Laravel)

In the file, this file defines many help functions and will be automatically loaded into the project through composer. Therefore, the functions can be accessed from any code location involved in http request processing, such as app().

2) Through the App Facade

<?php
Route::get(&#39;/&#39;, function () {
    dd(App::basePath());
    return &#39;&#39;;
});

The way to get the container instance through the App Facade is different from the above. You cannot assign the App to a variable first and then call the container through the variable. Methods. This is because App is just a class name, and we cannot copy a class name into a variable. $app = App; is not a legal executable statement, but $app = app(); is a legal executable statement, because it is followed by app(), which represents a function call. App::basePath(); is also a legal statement, it is calling the static method of the class.

Add two more points:

The first point: Facade is a special feature in the laravel framework. Each Facade will be associated with an instance object in the container. We can directly pass the Facade A class static method call is used to invoke methods on its associated instance object. For example, the Facade of App, when calling App::basePath(), is actually equivalent to app()->basePath().

This underlying mechanism also depends on the characteristics of the PHP language. It needs to set a static member in each Facade and associate it with an instance object of the service. When calling the static method of the Facade class , parse out the called method name, then call the method of the same name of the associated service instance, and finally return the result.

I think it is enough to understand what role Facade can play. It is not necessary to delve into its bottom layer to understand the implementation details. After all, in actual development, Facade is not used and it does not affect the use of the laravel framework at all. . In addition, in actual coding, it is very easy to customize a Facade. Just inherit the Facade base class encapsulated by laravel:

<?php
namespace ThirdProviders\CasServer\Facades;
use Illuminate\Support\Facades\Facade;
use ThirdProviders\CasServer\CasServerManager;
class CasServer extends Facade
{
    protected static function getFacadeAccessor()
    {
        return CasServerManager::class;
    }
}

Implement the getFacadeAccessor method of the Facade base class, and the laravel framework will know what this Facade class should be like Which service instance is associated. In fact, the name returned by this getFacadeAccess method is the service binding name to be introduced later. In the laravel container, a service instance will have a fixed binding name, and the instance can be found through this name. So why the Facade class only needs to return the service binding name.

We can look at the code of the App Facade class:

<?php
namespace Illuminate\Support\Facades;
/**
 * @see \Illuminate\Foundation\Application
 */
class App extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return &#39;app&#39;;
    }
}

Its getFacadeAccessor returns a string "app", which is the name used by the laravel container to bind itself. .

Second point: From the source code of the App Facade in the previous point, we can see that the full class name of the App Facade is actually: Illuminate\Support\Facades\App, so why can we pass it directly in the code? App can be accessed by the short name:

<?php
Route::get(&#39;/&#39;, function () {
    dd(App::basePath());
    return &#39;&#39;;
});

You see that the above code does not use use or fully qualified way to use Illuminate\Support\Facades\App. In fact, App is completely equivalent to Illuminate\Support\Facades\App, except that App is much shorter than Illuminate\Support\Facades\App and does not require use, so it is convenient to use. So how is it implemented? This is related to the alias configured in the laravel container. In config/app.php,

has a section of aliases specifically used to configure some types of aliases:

&#39;aliases&#39; => [
    &#39;App&#39; => Illuminate\Support\Facades\App::class,
    &#39;Artisan&#39; => Illuminate\Support\Facades\Artisan::class,
    &#39;Auth&#39; => Illuminate\Support\Facades\Auth::class,
    &#39;Blade&#39; => Illuminate\Support\Facades\Blade::class,
    &#39;Bus&#39; => Illuminate\Support\Facades\Bus::class,
    &#39;Cache&#39; => Illuminate\Support\Facades\Cache::class,
    &#39;Config&#39; => Illuminate\Support\Facades\Config::class,
    &#39;Cookie&#39; => Illuminate\Support\Facades\Cookie::class,
    &#39;Crypt&#39; => Illuminate\Support\Facades\Crypt::class,
    &#39;DB&#39; => Illuminate\Support\Facades\DB::class,
    &#39;Eloquent&#39; => Illuminate\Database\Eloquent\Model::class,
    &#39;Event&#39; => Illuminate\Support\Facades\Event::class,
    &#39;File&#39; => Illuminate\Support\Facades\File::class,
    &#39;Gate&#39; => Illuminate\Support\Facades\Gate::class,
    &#39;Hash&#39; => Illuminate\Support\Facades\Hash::class,
    &#39;Lang&#39; => Illuminate\Support\Facades\Lang::class,
    &#39;Log&#39; => Illuminate\Support\Facades\Log::class,
    &#39;Mail&#39; => Illuminate\Support\Facades\Mail::class,
    &#39;Notification&#39; => Illuminate\Support\Facades\Notification::class,
    &#39;Password&#39; => Illuminate\Support\Facades\Password::class,
    &#39;Queue&#39; => Illuminate\Support\Facades\Queue::class,
    &#39;Redirect&#39; => Illuminate\Support\Facades\Redirect::class,
    &#39;Redis&#39; => Illuminate\Support\Facades\Redis::class,
    &#39;Request&#39; => Illuminate\Support\Facades\Request::class,
    &#39;Response&#39; => Illuminate\Support\Facades\Response::class,
    &#39;Route&#39; => Illuminate\Support\Facades\Route::class,
    &#39;Schema&#39; => Illuminate\Support\Facades\Schema::class,
    &#39;Session&#39; => Illuminate\Support\Facades\Session::class,
    &#39;Storage&#39; => Illuminate\Support\Facades\Storage::class,
    &#39;URL&#39; => Illuminate\Support\Facades\URL::class,
    &#39;Validator&#39; => Illuminate\Support\Facades\Validator::class,
    &#39;View&#39; => Illuminate\Support\Facades\View::class
],

Then the request is processed in the laravel framework During the process, these aliases will be registered into the global environment through the Illuminate\Foundation\Bootstrap\RegisterFacades class:

<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Support\Facades\Facade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Contracts\Foundation\Application;
class RegisterFacades
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        Facade::clearResolvedInstances();
        Facade::setFacadeApplication($app);
        AliasLoader::getInstance($app->make(&#39;config&#39;)->get(&#39;app.aliases&#39;, []))->register();
    }
}

So we can directly use aliases instead of the complete type name to perform the same access function. If you have written some classes yourself with long names and are used a lot in the code, you can also consider configuring them in the config/app.php alias, and laravel will register them for us.

3) Another way to get the laravel container instance is to use $this->app

directly in the service provider. The service provider will be introduced later, but it is just introduced now. Because service provider classes are instantiated by the laravel container, these classes inherit from Illuminate\Support\ServiceProvider, which defines an instance attribute $app

Get the container instance in the code (Laravel)

laravel in When instantiating the service provider, the laravel container instance will be injected into the $app. So in the service provider, we can always access the laravel container instance through $this->$app, without using the app() function or App Facade.

For more laravel technical articles, please visit the laravel tutorial column!

The above is the detailed content of Get the container instance in the code (Laravel). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:杨子. If there is any infringement, please contact admin@php.cn delete