Swoole frame Hyperf (IV) - dependency injection

First do not understand, read, in the second half of this explanation is doing. In fact, we usually very common in this other framework, just do not know its name is called dependency injection.

For local and linux virtual machine implementation enjoyable synchronization code, it is possible by means of WinSCP automatically synchronize the local file with the server
I pulled the local framework
Here Insert Picture Description
are selected root directory
Here Insert Picture Description
and then you can directly edit the new file with an editor in the local, and will automatically synchronization to linux. Mainly in order to be able to press Ctrlto see the path.

text

Suppose we need IndexControllerto call within the UserServiceclass getInfoById(int $id)method.

App\Service\UserService.php

<?php
namespace App\Service;

class UserService
{
    public function getInfoById(int $id)
    {
        return $id;
    }
}

Injection via the constructor, this example only to facilitate understanding, without attention

App\Controller\IndexController.php

<?php
namespace App\Controller;

use App\Service\UserService;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController()
 */
class IndexController
{
    /**
     * @var UserService
     */
    private $userService;

    // 通过在构造函数的参数上声明参数类型完成自动注入
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function index()
    {
        $id = 123;
        // 直接使用
        return $this->userService->getInfoById($id);
    }
}
http://192.168.1.109:9501/index/index

By injecting @Inject comment

<?php
namespace App\Controller;

use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController()
 */
class IndexController
{
    /**
     * 通过 `@Inject` 注解注入由 `@var` 注解声明的属性类型对象
     *
     * @Inject
     * @var UserService
     */
    private $userService;

    public function index()
    {
        $id = 2333;
        // 直接使用
        return $this->userService->getInfoById($id);
    }
}
http://192.168.1.109:9501/index/index

Here Insert Picture Description

Noticed? In fact, I called a class.
Here Insert Picture Description
Arrow are the same class.

In fact, you do not need to make new it can be used directly in a class by @var index controller.
The way the constructor is not used @Inject, so you need to initialize the assignment via the constructor.

By adding @Injectannotations, the method can also be configured without using achieve the desired effect.

Hyperf frame Series List

Published 112 original articles · won praise 75 · views 130 000 +

Guess you like

Origin blog.csdn.net/weikaixxxxxx/article/details/96564078