Home  >  Article  >  PHP Framework  >  What is the core of laravel

What is the core of laravel

WBOY
WBOYOriginal
2022-03-11 16:34:002372browse

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;
    }
}

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);
    }
}

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) {}
}

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)
        );
        */
    }
}

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]);
        }
    }
}

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

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])
        );
        */
    }
}

可以看得出,我们不再需要在超人初始化之初,去初始化许多第三方类,只需初始化一个工厂类,即可满足需求。但这样似乎和以前区别不大,只是没有那么多 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]
    ]);

现在修改的结果令人满意。现在,“超人” 的创建不再依赖任何一个 “超能力” 的类,我们如若修改了或者增加了新的超能力,只需要针对修改 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:
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