先别看懂,先阅读,在后半部分讲解这个是干嘛的。其实这个我们平时在其它框架里很常用,就是不知道它的名字叫做依赖注入。
为了本地和linux虚拟机实现愉快的同步代码,所以可借助WinSCP 本地文件与服务器自动同步
我将框架拉到了本地
都选中根目录
然后就可以在本地用编辑器直接编辑与新建文件了,将会自动同步到linux。主要是为了能按Ctrl
看路径。
正文
假设我们需要在 IndexController
内调用 UserService
类的 getInfoById(int $id)
方法。
App\Service\UserService.php
<?php
namespace App\Service;
class UserService
{
public function getInfoById(int $id)
{
return $id;
}
}
通过构造方法注入,该例子只是便于理解,无需重视
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
通过 @Inject 注解注入
<?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
注意到了吗?其实就是调用了某个类。
箭头所指都是同一个类。
其实就是使你不需要去new而已,通过@var直接可在index控制器中使用某个类。
而构造方法的方式没有用到@Inject,所以需要通过构造方法初始化赋值。
通过加入@Inject
注解,就可以不使用构造方法也可达到效果。