PHPackages                             antaeus365/laravel-hx - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. antaeus365/laravel-hx

ActiveLibrary

antaeus365/laravel-hx
=====================

声明式、服务端驱动的HTMX UI框架 for Laravel

v1.0.2(1mo ago)01↑2900%MITPHPPHP ^8.1

Since Mar 28Pushed 1mo agoCompare

[ Source](https://github.com/antaeus365/laravel-hx)[ Packagist](https://packagist.org/packages/antaeus365/laravel-hx)[ RSS](/packages/antaeus365-laravel-hx/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (4)Used By (0)

Laravel HTMX Plugin
===================

[](#laravel-htmx-plugin)

一个声明式、服务端驱动的 HTMX UI 框架 for Laravel。

🎯 核心理念
------

[](#-核心理念)

- **UI = f(state) → HTML** - 纯粹的状态到HTML转换
- **只返回HTML** - 彻底告别JSON API
- **零前端状态** - 所有状态都在服务端管理
- **HTTP + HTML patch** - 所有交互都是HTTP请求和HTML片段更新

🚀 快速开始
------

[](#-快速开始)

### 1. 安装

[](#1-安装)

```
composer require antaeus365/laravel-hx
```

### 2. 发布配置

[](#2-发布配置)

```
php artisan vendor:publish --provider="Antaeus365\LaravelHx\HxServiceProvider"
```

### 3. 创建第一个组件

[](#3-创建第一个组件)

```
// app/Hx/Components/UserProfileComponent.php
namespace App\Hx\Components;

use Antaeus365\LaravelHx\HxComponent;

class UserProfileComponent extends HxComponent
{
    public string $name;
    public string $email;
    public bool $isActive = true;

    public function view(): string
    {
        return 'hx.components.user-profile';
    }

    public function actions(): array
    {
        return [
            'toggleStatus' => function() {
                $this->isActive = !$this->isActive;
                // 保存到数据库...
                return $this;
            },
            'updateEmail' => function() {
                // 更新邮箱逻辑...
                return $this;
            }
        ];
    }
}
```

### 4. 创建视图模板

[](#4-创建视图模板)

```
{{-- resources/views/hx/components/user-profile.blade.php --}}

    {{ $component->name }}
    Email: {{ $component->email }}
    Status: {{ $component->isActive ? 'Active' : 'Inactive' }}

        {{ $component->isActive ? 'Deactivate' : 'Activate' }}

```

### 5. 在Blade中使用

[](#5-在blade中使用)

```
{{-- 在任何Blade模板中 --}}

```

🔧 核心概念
------

[](#-核心概念)

### 组件 (Component)

[](#组件-component)

组件是唯一的抽象单位，包含：

- **状态** - public属性
- **视图** - view()方法返回模板名
- **动作** - actions()方法定义可执行的操作

### 路由系统

[](#路由系统)

自动为组件生成RESTful路由：

```
GET  /hx/user-profile/{id}           # 获取组件HTML
POST /hx/user-profile/{id}/toggleStatus  # 执行动作

```

### 动作 (Action)

[](#动作-action)

组件内部定义的动作会自动映射到路由：

```
public function actions(): array
{
    return [
        'toggleStatus' => fn() => $this->toggleUserStatus(),
        'delete' => fn() => $this->deleteUser(),
    ];
}
```

🛠️ 辅助函数
-------

[](#️-辅助函数)

### hx\_action()

[](#hx_action)

生成动作URL：

```

    Toggle Status

```

### hx\_component()

[](#hx_component)

生成组件URL：

```

```

🎨 Blade指令
---------

[](#-blade指令)

### @hxAction

[](#hxaction)

```

    Toggle

```

等价于：

```

    Toggle

```

🚀 高级功能
------

[](#-高级功能)

### 事件系统

[](#事件系统)

组件可以触发自定义事件：

```
public function actions(): array
{
    return [
        'save' => function() {
            // 保存数据...
            $this->trigger('user-saved', [
                'id' => $this->id,
                'name' => $this->name
            ]);
            return $this;
        }
    ];
}
```

在前端监听事件：

```
document.body.addEventListener('user-saved', function(evt) {
    console.log('用户已保存:', evt.detail);
});
```

### 多组件刷新

[](#多组件刷新)

同时刷新多个组件：

```
$this->hx->refresh([
    UserProfileComponent::class => $userId,
    UserStatsComponent::class => 'global',
    NotificationComponent::class => 1
]);
```

### 自定义响应头

[](#自定义响应头)

添加自定义HTMX响应头：

```
public function actions(): array
{
    return [
        'delete' => function() {
            // 删除逻辑...
            $this->header('HX-Location', '/dashboard');
            return $this;
        }
    ];
}
```

### 中间件支持

[](#中间件支持)

自动处理HTMX特定的请求头和响应：

```
// 在路由中使用
Route::middleware('hx')->group(function () {
    // HTMX路由组
});
```

### 自动错误处理

[](#自动错误处理)

验证错误自动转换为HTMX友好的响应：

```
// 组件动作中的验证
$data = request()->validate([
    'email' => 'required|email|unique:users'
]);
```

失败时自动返回422状态码和错误HTML片段。

📋 配置选项
------

[](#-配置选项)

```
// config/hx.php
return [
    'route_prefix' => 'hx',                    // 路由前缀
    'component_namespace' => 'App\\Hx\\Components', // 组件命名空间
    'component_views' => 'hx.components',      // 视图路径
    'auto_error_handling' => true,             // 自动错误处理
];
```

🧪 示例应用
------

[](#-示例应用)

查看 `examples/` 目录中的完整Todo应用示例。

📚 API参考
-------

[](#-api参考)

### HxComponent

[](#hxcomponent)

```
abstract class HxComponent
{
    // 设置ID
    public function setId(int $id): self

    // 获取ID
    public function getId(): ?int

    // 设置数据
    public function setData(array $data): self

    // 获取数据
    public function getData(): array

    // 渲染组件
    public function render(): View

    // 检查动作是否存在
    public function hasAction(string $actionName): bool

    // 获取组件标识符
    public function getIdentifier(): string
}
```

### HxManager

[](#hxmanager)

```
class HxManager
{
    // 注册组件
    public function component(string $componentClass): self

    // 添加OOB更新
    public function oob(string $view, array $data = []): self

    // 刷新组件
    public function refresh(array $components): self

    // 检查是否为HTMX请求
    public function isHtmxRequest(): bool
}
```

🎯 最佳实践
------

[](#-最佳实践)

1. **保持组件小巧** - 每个组件只负责一个功能
2. **使用明确的动作名称** - toggleStatus 比 toggle 更清晰
3. **合理使用OOB更新** - 用于全局通知或导航更新
4. **组件间通信** - 通过HX-Trigger事件系统

📄 许可证
-----

[](#-许可证)

MIT License

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance90

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

47d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cf5be4451aa1c8df6b80a16eedc80bacee8a7ecc1e9749cdc82ab412608d0ec9?d=identicon)[antaeus365](/maintainers/antaeus365)

---

Top Contributors

[![antaeus365](https://avatars.githubusercontent.com/u/142164776?v=4)](https://github.com/antaeus365 "antaeus365 (5 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/antaeus365-laravel-hx/health.svg)

```
[![Health](https://phpackages.com/badges/antaeus365-laravel-hx/health.svg)](https://phpackages.com/packages/antaeus365-laravel-hx)
```

###  Alternatives

[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[laravel/cashier-paddle

Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.

264778.4k3](/packages/laravel-cashier-paddle)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[laravellux/html

HTML and Form Builders for the Laravel Framework

35239.2k3](/packages/laravellux-html)[konekt/html

HTML and Form Builders for the Laravel Framework

24403.2k5](/packages/konekt-html)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
