hyperf的使用

hyperf是swoole的封装框架,用起来效率还是不错的.

使用方式看手册

https://hyperf.wiki/2.2/#/zh-cn/quick-start/install

其实是靠composer

composer create-project hyperf/hyperf-skeleton 

之后就是会询问安装那些你想要的包

然后我就同意了 redis cache tarce等等,之后就是要加载模板啥的

用这个 composer require hyperf/view  php bin/hyperf.php vendor:publish hyperf/view

还有 composer require hyperf/task 

安装blade引擎

composer require hyperf/view-engine

安装thinkTemplate引擎

composer require sy-records/think-template

这个引擎需要写个文件来实现他接口(vendor/sy-records/think-template/src/TemplateEngine.php)

<?php

declare(strict_types=1);
namespace think;

use Hyperf\View\Engine\EngineInterface;
use think\Template;

class TemplateEngine implements EngineInterface
{
    public function render($template, $data, $config): string
    {
        // 实例化对应的模板引擎的实例
        $engine = new Template($config);
        // 并调用对应的渲染方法
        return $engine->fetch($template, $data);
    }
}
View Code

之后配置composer.json如下

{
    "name": "hyperf/hyperf-skeleton",
    "type": "project",
    "keywords": [
        "php",
        "swoole",
        "framework",
        "hyperf",
        "microservice",
        "middleware"
    ],
    "description": "A coroutine framework that focuses on hyperspeed and flexible, specifically use for build microservices and middlewares.",
    "license": "Apache-2.0",
    "require": {
        "php": ">=7.3",
        "hyperf/cache": "~2.2.0",
        "hyperf/command": "~2.2.0",
        "hyperf/config": "~2.2.0",
        "hyperf/database": "~2.2.0",
        "hyperf/db-connection": "~2.2.0",
        "hyperf/framework": "~2.2.0",
        "hyperf/guzzle": "~2.2.0",
        "hyperf/http-server": "~2.2.0",
        "hyperf/logger": "~2.2.0",
        "hyperf/memory": "~2.2.0",
        "hyperf/model-cache": "~2.2.0",
        "hyperf/process": "~2.2.0",
        "hyperf/redis": "~2.2.0",
        "hyperf/task": "^2.2",
        "hyperf/tracer": "~2.2.0",
        "hyperf/view": "^2.2",
        "hyperf/view-engine": "^2.2",
        "sy-records/think-template": "^2.0"
    },
    "require-dev": {
        "friendsofphp/php-cs-fixer": "^3.0",
        "hyperf/devtool": "~2.2.0",
        "hyperf/ide-helper": "~2.2.0",
        "hyperf/testing": "~2.2.0",
        "mockery/mockery": "^1.0",
        "phpstan/phpstan": "^0.12",
        "swoole/ide-helper": "^4.5"
    },
    "suggest": {
        "ext-openssl": "Required to use HTTPS.",
        "ext-json": "Required to use JSON.",
        "ext-pdo": "Required to use MySQL Client.",
        "ext-pdo_mysql": "Required to use MySQL Client.",
        "ext-redis": "Required to use Redis Client."
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": []
    },
    "autoload-dev": {
        "psr-4": {
            "HyperfTest\\": "./test/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "optimize-autoloader": true,
        "sort-packages": true
    },
    "extra": [],
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-autoload-dump": [
            "rm -rf runtime/container"
        ],
        "test": "co-phpunit --prepend test/bootstrap.php -c phpunit.xml --colors=always",
        "cs-fix": "php-cs-fixer fix $1",
        "analyse": "phpstan analyse --memory-limit 300M -l 0 -c phpstan.neon ./app ./config",
        "start": [
            "Composer\\Config::disableProcessTimeout",
            "php ./bin/hyperf.php start"
        ]
    }
}
View Code

view.php配置如下

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\View\Engine\NoneEngine;
use Hyperf\View\Mode;

return [
    // 使用的渲染引擎
    // 'engine' => NoneEngine::class,
    // 'engine' => Hyperf\ViewEngine\HyperfViewEngine::class,
    'engine' => think\TemplateEngine::class,
    // 不填写则默认为 Task 模式,推荐使用 Task 模式
    'mode' => Mode::TASK,
    'config' => [
        'view_path' => BASE_PATH . '/storage/view/',
        'cache_path' => BASE_PATH . '/runtime/view/',
    ],
];
View Code

server.php配置如下

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;

return [
    'mode' => SWOOLE_PROCESS,
    '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'],
            ],
        ],
    ],
    'settings' => [
        Constant::OPTION_ENABLE_COROUTINE => true,
        Constant::OPTION_WORKER_NUM => swoole_cpu_num(),
        Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
        Constant::OPTION_OPEN_TCP_NODELAY => true,
        Constant::OPTION_MAX_COROUTINE => 100000,
        Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
        Constant::OPTION_MAX_REQUEST => 100000,
        Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
        Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
        'task_worker_num' => 8,// Task Worker 数量,根据您的服务器配置而配置适当的数量
        'task_enable_coroutine' => false,// 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况
        // 静态资源
        'document_root' => BASE_PATH . '/static',
        'enable_static_handler' => true,
    ],
    'callbacks' => [
        Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
        Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
        Event::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'],
        Event::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'],
    ],
];
View Code

建立文件夹 

static 
storage/view/
runtime/view/
里面放你要的模板文件storage/view/index.blade.php(给blade用的)和storage/view/view_index.html(给thinkTemplate用的)
然后这个view就能生效了就能访问模板文件了
<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\View\RenderInterface;

/**
 * @AutoController
 */
class ViewController
{
    public function index(RenderInterface $render)
    {
        return $render->render('view_index', ['name' => 'Hyperf']);
    }
}

路由config/routes.php再加一下

Router::addRoute(['GET', 'POST', 'HEAD'], '/view/', 'App\Controller\ViewController::index');

访问http://域名/view就能加载视图模板了

访问静态文件的话需要在static/下面放个index.js

启动:

php bin/hyperf.php start

这样就能访问了

另外这里提一句如何使用nginx作为服务器转发local.hyperf.com给swoole运行

来到/etc/nginx/sites-available 创建文件local.hyperf.com

内容如下:

# 至少需要一个 Hyperf 节点,多个配置多行
upstream hyperf {
    # Hyperf HTTP Server 的 IP 及 端口
    server 127.0.0.1:9501;
}
server {
    # 监听端口
    listen 80; 
    # 绑定的域名,填写您的域名
    server_name local.hyperf.com;
    location / {
        # 将客户端的 Host 和 IP 信息一并转发到对应节点  
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # 转发Cookie,设置 SameSite
        proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";
        # 执行代理访问真实服务器
        proxy_pass http://127.0.0.1:9501;
    }
}

然后来到/etc/nginx/sites-enabled

创建软链接

sudo ln -s ../sites-available/local.hyperf.com local.hyperf.com

重启nginx

别忘了改一下hosts文件在/etc/hosts

127.0.0.1 local.hyperf.com

结束后就可以访问了 http://local.hyperf.com/

posted @ 2022-03-03 10:16  李照耀  阅读(1507)  评论(1编辑  收藏  举报