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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM