search
Homephp教程PHP开发Laravel dependency injection idea

Dependency injection

Dependency injection is a fancy term, but it actually means: the dependencies of a class are "injected" through the constructor or in some cases through the "setter" method. Let’s first look at a code example in a Laravel controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use App\Users\Repository as UserRepository;

class UserController extends Controller
{
    /**
     * 用户 Repository 的实例。
     */
    protected $users;

    /**
     * 创建一个新的控制器实例。
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    /**
     * 显示指定 ID 的用户。
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        $user_info = $this->users->find($id);
        return view(&#39;user&#39;, [&#39;user_info&#39; => $user_info]);
    }
}

Laravel manages class dependencies and performs dependency injection through service containers. If you use an interface as a type hint for function parameters, you need to bind the specified implementation to the interface:

interface EventPusher {
    public function send($data);
}
class RedisEventPusher implements EventPusher {
    public function send($data) {
        //
    }
}
$this->app->bind(&#39;App\Contracts\EventPusher&#39;, &#39;App\Services\RedisEventPusher&#39;);
use App\Contracts\EventPusher;

/**
 * 创建一个新的类实例。
 *
 * @param  EventPusher  $pusher
 * @return void
 */
public function __construct(EventPusher $pusher)
{
    $this->pusher = $pusher;
}

This is the so-called interface-oriented programming. The interface can be understood as a specification and a constraint. High-level modules do not directly depend on low-level modules, they should all depend on abstractions (referred to as interfaces).

The most important benefit of using dependency injection is that it effectively separates the object and the external resources it requires, making them loosely coupled, which is conducive to function reuse. More importantly, it makes the entire architecture of the program very flexible. .

Inversion of Control

Inversion of Control (Inversion of Control, abbreviated as IoC) is a design principle in object-oriented programming. The most common method is called Dependency Injection (DI), and the other method is called "Dependency Lookup". Through inversion of control, when an object is created, an external entity that controls all objects in the system passes the reference of the object it depends on to it. It can also be said that dependencies are injected into the object.

Laravel dependency injection idea

<?php
/**
 * 没有IoC/DI的时候,常规的A类使用C类的示例
 */

/**
 * Class c
 */
class c
{
    public function say()
    {
        echo &#39;hello&#39;;
    }
}

/**
 * Class a
 */
class a
{
    private $c;
    public function __construct()
    {
        $this->c = new C(); // 实例化创建C类
    }

    public function sayC()
    {
        echo $this->c->say(); // 调用C类中的方法
    }
}

$a = new a();
$a->sayC();

When there is an IoC/DI container, class A no longer actively creates C, as shown in the figure below:

Laravel dependency injection idea

Instead, it passively waits for the IoC/DI container to obtain a C instance, and then reversely inject it into class A, as shown in the figure below:

Laravel dependency injection idea

<?php
/**
 * 当有了IoC/DI的容器后,a类依赖c实例注入的示例
 */

/**
 * Class c
 */
class c
{
    public function say()
    {
        echo &#39;hello&#39;;
    }
}

/**
 * Class a
 */
class a
{
    private $c;
    public function setC(C $c)
    {
        $this->c = $c; // 实例化创建C类
    }

    public function sayC()
    {
        echo $this->c->say(); // 调用C类中的方法
    }
}

$c = new C();
$a = new a();
$a->setC($c);
$a->sayC();


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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment