安装
基于swoole安装:
composer create-project hyperf/hyperf-skeleton
基于swow安装:
composer create-project hyperf/swow-skeleton
启动:
cd hyperf-skeleton
php bin/hyperf.php start
编辑
由于每次更新代码都需要重启服务很麻烦。
Watcher是hyperf热更的一种办法
composer require hyperf/watcher --dev ##安装
php bin/hyperf.php vendor:publish hyperf/watcher ##生成配置文件
config/autoload/watcher.php ##配置文件所在目录
启动Watcher
php bin/hyperf.php server:watch
路由
1.传统路由
直接在routes.php加就可以了
Router::addRoute(['GET', 'POST', 'HEAD'], '/', 'App\Controller\IndexController@index');
2.注解路由
首先我们需要下载phpstrom的IDE注解插件PHP Annotations,重启PHPstrom
AutoController方式:
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
/**
* @AutoController(prefix="user")
* prefix参数会重定义类名 使Url自定义
*/
class IndexController extends AbstractController
{
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
return [
'method' => $method,
'message' => "Hello {$user}.",
];
}
}
如果没有加prefix参数的话 url是http://localhost:9501/index/index
如果定义了prefix参数 url就是 http://localhost:9501/user/index
Controller()方式
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
/**
* @Controller(prefix="index")
*/
class IndexController extends AbstractController
{
/**
* @RequestMapping(path="index", methods={"get","post"})
* #path规定了路由里对应该方法的名称,methods则规定了访问的方式
* 注意参数要带引号而且必须是双引号
*/
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
return [
'method' => $method,
'message' => "Hello {$user}.",
];
}
}
@Controller()注解需要搭配 @RequestMapping() @GetMapping() @PutMapping() @PostMapping()等注解来一起使用
依赖注入
依赖注入有两种方法:
通过构造函数注入
// 在构造函数声明参数的类型,Hyperf 会自动注入对应的对象或值
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
另一种使用注解的方法
/**
* @Inject()
* @var UserService
*/
private $userService;
多端口监听
config/autoload/dependencies.php
<?php
return [
'InnerHttp' => Hyperf\HttpServer\Server::class,
];
config/autoload/server.php
<?php
return [
'servers' => [
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9501,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
],
[
'name' => 'innerHttp',
'type' => Server::SERVER_HTTP,
'host' => '0.0.0.0',
'port' => 9502,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => ['InnerHttp', 'onRequest'],
],
],
]
];
路由指向
<?php
//传统路由
Router::addServer('innerHttp', function () {
Router::get('/', 'App\Controller\IndexController@index');
});
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
//注解路由
/**
* @AutoController(server="innerHttp")
*/
class IndexController
{
public function index()
{
return 'Hello World.';
}
}