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

Get the container instance in the code (Laravel)

Aug 06, 2021 am 09:35 AM
laravel

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();
Copy after login

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;;
});
Copy after login
Copy after login

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;
    }
}
Copy after login

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;;
    }
}
Copy after login

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;;
});
Copy after login
Copy after login

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
],
Copy after login

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();
    }
}
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles