Hyperf Nano介绍:零配置的极简Hyperf发行版

Hyperf Nano介绍:零配置的极简Hyperf发行版

【免费下载链接】hyperf 🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease. 【免费下载链接】hyperf 项目地址: https://gitcode.com/hyperf/hyperf

痛点:传统框架的配置复杂性

还在为繁琐的框架配置而头疼吗?每次新建项目都要重复搭建骨架、配置环境、编写样板代码?传统PHP框架往往需要大量的前期配置工作,这对于快速原型开发、微服务场景或者简单的API服务来说显得过于沉重。

Hyperf Nano应运而生,它是一款革命性的极简Hyperf发行版,彻底颠覆了传统框架的使用方式。通过Nano,您可以在零配置、无骨架的情况下,仅用一个PHP文件就能快速搭建完整的Hyperf应用。

什么是Hyperf Nano?

Hyperf Nano是Hyperf框架的极简发行版,它将Hyperf的强大功能浓缩到最小化的形式中。Nano保留了Hyperf的所有核心特性,但移除了复杂的项目结构和繁琐的配置要求。

核心特性对比

特性传统HyperfHyperf Nano
项目结构完整的骨架目录单文件即可运行
配置要求需要多个配置文件零配置,按需配置
启动速度相对较慢极速启动
开发方式注解驱动闭包风格为主
适用场景大型项目微服务、快速原型

快速入门:5分钟搭建你的第一个Nano应用

环境要求

  • PHP >= 7.3
  • Swoole >= 4.5

安装步骤

# 创建项目目录
mkdir my-nano-app
cd my-nano-app

# 初始化Composer
composer init

# 安装Hyperf Nano
composer require hyperf/nano

创建你的第一个应用

<?php
// index.php
use Hyperf\Nano\Factory\AppFactory;

require_once __DIR__ . '/vendor/autoload.php';

// 创建应用实例,监听0.0.0.0:9051
$app = AppFactory::create('0.0.0.0', 9051);

// 定义路由处理程序
$app->get('/', function () {
    $user = $this->request->input('user', 'nano');
    $method = $this->request->getMethod();

    return [
        'message' => "hello {$user}",
        'method' => $method,
        'timestamp' => time()
    ];
});

// 启动应用
$app->run();

运行应用

php index.php start

访问 http://localhost:9051?user=world,你将立即看到响应:

{
  "message": "hello world",
  "method": "GET",
  "timestamp": 1725060828
}

Nano的核心功能详解

1. 灵活的路由系统

Nano支持所有标准HTTP方法的路由定义:

$app->get('/users', function () {
    return ['action' => 'get users'];
});

$app->post('/users', function () {
    return ['action' => 'create user'];
});

$app->put('/users/{id}', function ($id) {
    return ['action' => 'update user', 'id' => $id];
});

$app->delete('/users/{id}', function ($id) {
    return ['action' => 'delete user', 'id' => $id];
});

// 路由分组
$app->addGroup('/api/v1', function () use ($app) {
    $app->get('/products', function () {
        return ['version' => 'v1', 'data' => 'products'];
    });
});

2. 依赖注入容器集成

Nano完美集成Hyperf的DI容器:

class UserService {
    public function getUsers() {
        return ['user1', 'user2', 'user3'];
    }
}

// 注册服务到容器
$app->getContainer()->set(UserService::class, new UserService());

$app->get('/users', function () {
    /** @var \Hyperf\Nano\ContainerProxy $this */
    $userService = $this->get(UserService::class);
    return $userService->getUsers();
});

3. 中间件支持

// 添加全局中间件
$app->addMiddleware(function ($request, $handler) {
    // 前置处理
    $request = $request->withAttribute('start_time', microtime(true));
    
    $response = $handler->handle($request);
    
    // 后置处理
    $duration = microtime(true) - $request->getAttribute('start_time');
    return $response->withHeader('X-Response-Time', $duration . 's');
});

// 路由特定中间件
$app->get('/admin', function () {
    return 'Admin area';
})->addMiddleware(function ($request, $handler) {
    // 权限检查逻辑
    if (!$request->getHeader('Authorization')) {
        return new \Hyperf\HttpMessage\Base\Response(401);
    }
    return $handler->handle($request);
});

4. 异常处理机制

$app->addExceptionHandler(function ($throwable, $response) {
    $statusCode = 500;
    $message = 'Internal Server Error';
    
    if ($throwable instanceof \Hyperf\HttpServer\Exception\HttpException) {
        $statusCode = $throwable->getStatusCode();
        $message = $throwable->getMessage();
    }
    
    return $response->withStatus($statusCode)
        ->withBody(new \Hyperf\HttpMessage\Stream\SwooleStream(json_encode([
            'error' => $message,
            'code' => $statusCode
        ])));
});

高级功能示例

定时任务(Crontab)

use Hyperf\Contract\StdoutLoggerInterface;

$app->addCrontab('* * * * *', function () {
    $this->get(StdoutLoggerInterface::class)->info('每分钟执行一次定时任务');
});

$app->addCrontab('0 */2 * * *', function () {
    $this->get(StdoutLoggerInterface::class)->info('每两小时执行一次任务');
});

自定义进程

$app->addProcess(function () {
    while (true) {
        // 后台处理任务
        $this->get(StdoutLoggerInterface::class)->info('后台进程运行中...');
        sleep(10);
    }
});

事件监听

use Hyperf\Framework\Event\BootApplication;

$app->addListener(BootApplication::class, function ($event) {
    $this->get(StdoutLoggerInterface::class)->info('应用启动完成');
});

数据库操作

$app->config([
    'db.default' => [
        'host' => getenv('DB_HOST') ?: 'localhost',
        'port' => getenv('DB_PORT') ?: 3306,
        'database' => getenv('DB_DATABASE') ?: 'test',
        'username' => getenv('DB_USERNAME') ?: 'root',
        'password' => getenv('DB_PASSWORD') ?: '',
    ]
]);

$app->get('/users', function () {
    $users = \Hyperf\DB\DB::query('SELECT * FROM users LIMIT 10');
    return $users;
});

实战:构建完整的RESTful API

下面是一个完整的用户管理API示例:

<?php
use Hyperf\Nano\Factory\AppFactory;
use Hyperf\DB\DB;

require_once __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create('0.0.0.0', 9501);

// 数据库配置
$app->config([
    'db.default' => [
        'host' => 'localhost',
        'port' => 3306,
        'database' => 'user_management',
        'username' => 'root',
        'password' => 'password',
    ]
]);

// 用户列表
$app->get('/users', function () {
    $users = DB::query('SELECT * FROM users WHERE deleted = 0');
    return ['data' => $users];
});

// 创建用户
$app->post('/users', function () {
    $data = $this->request->getParsedBody();
    $result = DB::query(
        'INSERT INTO users (name, email, created_at) VALUES (?, ?, ?)',
        [$data['name'], $data['email'], date('Y-m-d H:i:s')]
    );
    return ['id' => $result->insertId, 'message' => 'User created'];
});

// 用户详情
$app->get('/users/{id}', function ($id) {
    $user = DB::query('SELECT * FROM users WHERE id = ? AND deleted = 0', [$id]);
    if (empty($user)) {
        return ['error' => 'User not found'], 404;
    }
    return ['data' => $user[0]];
});

// 更新用户
$app->put('/users/{id}', function ($id) {
    $data = $this->request->getParsedBody();
    DB::query(
        'UPDATE users SET name = ?, email = ?, updated_at = ? WHERE id = ?',
        [$data['name'], $data['email'], date('Y-m-d H:i:s'), $id]
    );
    return ['message' => 'User updated'];
});

// 删除用户
$app->delete('/users/{id}', function ($id) {
    DB::query('UPDATE users SET deleted = 1 WHERE id = ?', [$id]);
    return ['message' => 'User deleted'];
});

// 错误处理中间件
$app->addMiddleware(function ($request, $handler) {
    try {
        return $handler->handle($request);
    } catch (\Throwable $e) {
        return new \Hyperf\HttpMessage\Base\Response(500, [], json_encode([
            'error' => 'Internal Server Error',
            'message' => $e->getMessage()
        ]));
    }
});

$app->run();

性能优化建议

1. 使用OPCache

; php.ini配置
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000

2. 合理配置Swoole

$app = AppFactory::create('0.0.0.0', 9501);
$app->setOptions([
    'worker_num' => swoole_cpu_num(),
    'max_request' => 10000,
    'enable_static_handler' => true,
    'document_root' => __DIR__ . '/public'
]);

3. 使用连接池

对于数据库、Redis等资源,建议使用连接池管理连接,避免频繁创建和销毁连接。

适用场景分析

推荐使用场景

  1. 微服务架构 - 每个服务可以是一个独立的Nano应用
  2. 快速原型开发 - 快速验证想法和概念
  3. 简单的API服务 - 轻量级的RESTful API
  4. 命令行工具 - 基于Swoole的命令行应用
  5. 定时任务服务 - 独立的定时任务处理器

不推荐场景

  1. 大型单体应用 - 复杂的业务逻辑需要更完善的项目结构
  2. 需要大量注解的场景 - Nano主要使用闭包风格
  3. 复杂的依赖管理 - 需要精细控制依赖关系的项目

总结

Hyperf Nano代表了PHP框架发展的新方向——极简化、零配置、快速启动。它完美解决了传统框架配置复杂、启动缓慢的问题,特别适合现代微服务架构和快速开发场景。

通过Nano,开发者可以:

  • 🚀 在几分钟内搭建可用的Web服务
  • 📦 享受Hyperf全部功能的轻量级版本
  • 🔧 按需添加功能,避免不必要的复杂性
  • 🎯 专注于业务逻辑而不是框架配置

无论你是想要快速验证一个想法,还是构建轻量级的微服务,Hyperf Nano都是一个绝佳的选择。它证明了"简单就是美"的哲学在现代Web开发中仍然具有强大的生命力。

现在就尝试使用Hyperf Nano,体验极简开发带来的效率和乐趣吧!

【免费下载链接】hyperf 🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease. 【免费下载链接】hyperf 项目地址: https://gitcode.com/hyperf/hyperf

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值