Table of Contents
What is the core of laravel
Home PHP Framework Laravel What is the core of laravel

What is the core of laravel

Mar 11, 2022 pm 04:34 PM
laravel

The core of laravel is the service container, which is the IOC container. The container provides a series of services needed in the entire framework, including dependency injection and control inversion. Inversion of control is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. .

What is the core of laravel

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

What is the core of laravel

The service container, also called the IOC container, actually contains two parts: dependency injection (DI) and inversion of control (IOC), and is the real core of laravel. Various other functional modules such as Route (routing), Eloquent ORM (database ORM component), Request and Response (request and response), etc., are actually provided by class modules that have nothing to do with the core. These classes are registered from From instantiation to final use by you, laravel's service container is actually responsible for it. The concept of service container is difficult to explain clearly. It can only be explained step by step from the history of the service container.

This container provides a series of services needed in the entire framework.

The Story of the Birth of IoC Containers - The Stone Age (Original Mode)

We regard a "Superman" as a class,

class Superman {}

We can imagine that a superman must have at least one superpower when he is born. This superpower can also be abstracted into an object. Let's define a class for this object to describe him. A superpower must have multiple attributes and (operation) methods. You can imagine this freely, but for now we will roughly define a "superpower" that only has attributes. As for what it can do, we will enrich it later:

class Power {
    /**
     * 能力值
     */
    protected $ability;
    /**
     * 能力范围或距离
     */
    protected $range;
    public function __construct($ability, $range)
    {
        $this->ability = $ability;
        $this->range = $range;
    }
}
Copy after login

At this time we go back and modify the previous "Superman" class so that a "Superman" is given a super power when it is created:

class Superman
{
    protected $power;
    public function __construct()
    {
        $this->power = new Power(999, 100);
    }
}
Copy after login

In this case, when we create a "Superman" instance , and also created an instance of "super power". However, we have seen that there is an inevitable dependence between "superman" and "super power".

The so-called "dependence" means "if I rely on you, there will be no me without you."

In a project that implements object-oriented programming, such dependencies can be seen everywhere. A small amount of dependence does not have a very intuitive impact. As we gradually unfold this example, we will gradually realize what a nightmare experience it is when dependence reaches a certain level. Of course, I will also naturally explain how to solve the problem.

In the previous example, the superpower class is a specific superpower after instantiation, but we know that Superman’s superpowers are diversified, and each superpower has its own methods and attributes. The differences cannot be completely described by one type. Let's make modifications now. Let's assume that Superman can have the following superpowers:

Flight, attributes are: flight speed, duration of flight

Brute force, attributes are: strength value

Energy bombs, attributes include: damage value, shooting distance, number of simultaneous shots

We created the following categories:

class Flight
{
    protected $speed;
    protected $holdtime;
    public function __construct($speed, $holdtime) {}
}
class Force
{
    protected $force;
    public function __construct($force) {}
}
class Shot
{
    protected $atk;
    protected $range;
    protected $limit;
    public function __construct($atk, $range, $limit) {}
}
Copy after login

Okay, now our Superman is a bit "busy" . When Superman is initialized, will we instantiate the superpowers he possesses as needed? It is roughly as follows:

class Superman
{
    protected $power;
    public function __construct()
    {
        $this->power = new Fight(9, 100);
        // $this->power = new Force(45);
        // $this->power = new Shot(99, 50, 2);
        /*
        $this->power = array(
            new Force(45),
            new Shot(99, 50, 2)
        );
        */
    }
}
Copy after login

We need to manually instantiate a series of needs in the constructor (or other methods) class, this is not good. It is conceivable that if the needs change (different monsters run rampant on the earth), more targeted new superpowers are needed, or the method of superpowers needs to be changed, we must reinvent Superman. In other words, while changing my superpowers, I also have to create a new superman. The efficiency is too low! The world had already been destroyed before the new Superman was created.

At this time, the person who had an idea thought: Why can't it be like this? Superman's abilities can be changed at any time, just by adding or updating a chip or other device (Iron Man comes to mind). In this case, there is no need to start over again.

The Story of the Birth of IoC Containers - The Bronze Age (Factory Mode)

We should not manually solidify his "superpower" initialization behavior in the "Superman" class, but instead The outside is responsible for creating superpower modules, devices or chips from the outside (we will refer to them as "modules" from now on), and implanting them into a certain interface in Superman's body. This interface is a given, as long as this "module" satisfies The devices in this interface can be used by Superman to enhance and increase a certain ability of Superman. This behavior of making the outside world responsible for its dependency requirements can be called "Inversion of Control (IoC)".

Factory mode, as the name suggests, is a development mode in which all instances of external things that a class depends on can be created by one or more "factories", which is the "factory mode".

In order to make superpower modules for Superman, we created a factory that can make a variety of modules and only need to use one method:

class SuperModuleFactory
{
    public function makeModule($moduleName, $options)
    {
        switch ($moduleName) {
            case 'Fight':     return new Fight($options[0], $options[1]);
            case 'Force':     return new Force($options[0]);
            case 'Shot':     return new Shot($options[0], $options[1], $options[2]);
        }
    }
}
Copy after login

这时候,超人 创建之初就可以使用这个工厂!

class Superman
{
    protected $power;
    public function __construct()
    {
        // 初始化工厂
        $factory = new SuperModuleFactory;
        // 通过工厂提供的方法制造需要的模块
        $this->power = $factory->makeModule('Fight', [9, 100]);
        // $this->power = $factory->makeModule('Force', [45]);
        // $this->power = $factory->makeModule('Shot', [99, 50, 2]);
        /*
        $this->power = array(
            $factory->makeModule('Force', [45]),
            $factory->makeModule('Shot', [99, 50, 2])
        );
        */
    }
}
Copy after login

可以看得出,我们不再需要在超人初始化之初,去初始化许多第三方类,只需初始化一个工厂类,即可满足需求。但这样似乎和以前区别不大,只是没有那么多 new 关键字。其实我们稍微改造一下这个类,你就明白,工厂类的真正意义和价值了。

class Superman
{
    protected $power;
    public function __construct(array $modules)
    {
        // 初始化工厂
        $factory = new SuperModuleFactory;
        // 通过工厂提供的方法制造需要的模块
        foreach ($modules as $moduleName => $moduleOptions) {
            $this->power[] = $factory->makeModule($moduleName, $moduleOptions);
        }
    }
}
// 创建超人
$superman = new Superman([
    'Fight' => [9, 100],
    'Shot' => [99, 50, 2]
    ]);
Copy after login

现在修改的结果令人满意。现在,“超人” 的创建不再依赖任何一个 “超能力” 的类,我们如若修改了或者增加了新的超能力,只需要针对修改 SuperModuleFactory 即可。

【相关推荐:laravel视频教程

The above is the detailed content of What is the core of 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 - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel - Pagination Customizations Laravel - Pagination Customizations Aug 27, 2024 am 10:51 AM

Laravel - Pagination Customizations - Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatical

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

See all articles