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
are selected root directory
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 Ctrl
to see the path.
text
Suppose we need IndexController
to call within the UserService
class 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
Noticed? In fact, I called a class.
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 @Inject
annotations, the method can also be configured without using achieve the desired effect.