beyondcode/claude-hooks-sdk 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

beyondcode/claude-hooks-sdk

Composer 安装命令:

composer require beyondcode/claude-hooks-sdk

包简介

A PHP SDK for building Claude Code hooks.

README 文档

README

Latest Version on Packagist Tests Total Downloads

A Laravel-inspired PHP SDK for building Claude Code hook responses with a clean, fluent API. This SDK makes it easy to create structured JSON responses for Claude Code hooks using an expressive, chainable interface.

Claude Code hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle, providing deterministic control over its behavior. For more details, see the Claude Code Hooks documentation.

Installation

You can install the package via composer:

composer require beyondcode/claude-hooks-sdk

Usage

Creating a Claude Hook

Here's how to create a PHP script that Claude Code can use as a hook:

Step 1: Create your PHP hook script

Create a new PHP file (e.g., validate-code.php) using the SDK:

<?php

require 'vendor/autoload.php';

use BeyondCode\ClaudeHooks\ClaudeHook;

// Read the hook data from stdin. 
// This will automatically return the correct Hook instance (for example PreToolUse)
$hook = ClaudeHook::create();

// Example: Validate bash commands
if ($hook->toolName() === 'Bash') {
    $command = $hook->toolInput('command', '');
    
    // Check for potentially dangerous commands
    if (str_contains($command, 'rm -rf')) {
        // Block the tool call with feedback
        $hook->response()->block('Dangerous command detected. Use caution with rm -rf commands.');
    }
}

// Allow other tool calls to proceed
$hook->success();

Step 2: Register your hook in Claude Code

  1. Run the /hooks command in Claude Code
  2. Select the PreToolUse hook event (runs before tool execution)
  3. Add a matcher (e.g., Bash to match shell commands)
  4. Add your hook command: php /path/to/your/validate-code.php
  5. Save to user or project settings

Your hook is now active and will validate commands before Claude Code executes them!

Hook Types and Methods

The SDK automatically creates the appropriate hook type based on the input:

use BeyondCode\ClaudeHooks\ClaudeHook;
use BeyondCode\ClaudeHooks\Hooks\{PreToolUse, PostToolUse, Notification, Stop, SubagentStop};

$hook = ClaudeHook::create();

if ($hook instanceof PreToolUse) {
    $toolName = $hook->toolName();           // e.g., "Bash", "Write", "Edit"
    $toolInput = $hook->toolInput();         // Full input array
    $filePath = $hook->toolInput('file_path'); // Specific input value
}

if ($hook instanceof PostToolUse) {
    $toolResponse = $hook->toolResponse();   // Full response array
    $success = $hook->toolResponse('success', true); // With default value
}

if ($hook instanceof Notification) {
    $message = $hook->message();
    $title = $hook->title();
}

if ($hook instanceof Stop || $hook instanceof SubagentStop) {
    $isActive = $hook->stopHookActive();
}

Response Methods

All hooks provide a fluent response API:

// Continue processing (default behavior)
$hook->response()->continue();

// Stop Claude from continuing with a reason
$hook->response()->stop('Reason for stopping');

// For PreToolUse: approve or block tool calls
$hook->response()->approve('Optional approval message')->continue();
$hook->response()->block('Required reason for blocking')->continue();

// Suppress output from transcript mode
$hook->response()->suppressOutput()->continue();

Example Hooks

Code Formatter Hook

Automatically format PHP files after edits:

<?php

require 'vendor/autoload.php';

use BeyondCode\ClaudeHooks\ClaudeHook;
use BeyondCode\ClaudeHooks\Hooks\PostToolUse;

$hook = ClaudeHook::create();

$filePath = $hook->toolInput('file_path', '');

if (str_ends_with($filePath, '.php')) {
    exec("php-cs-fixer fix $filePath", $output, $exitCode);
    
    if ($exitCode !== 0) {
        $hook->response()
            ->suppressOutput()
            ->merge(['error' => 'Formatting failed'])
            ->continue();
    }
}

Security Validator Hook

Prevent modifications to sensitive files:

#!/usr/bin/env php
<?php

require 'vendor/autoload.php';

use BeyondCode\ClaudeHooks\ClaudeHook;
use BeyondCode\ClaudeHooks\Hooks\PreToolUse;

$hook = ClaudeHook::fromStdin(file_get_contents('php://stdin'));

if ($hook instanceof PreToolUse) {
    // Check file-modifying tools
    if (in_array($hook->toolName(), ['Write', 'Edit', 'MultiEdit'])) {
        $filePath = $hook->toolInput('file_path', '');
        
        $sensitivePatterns = [
            '.env',
            'config/database.php',
            'storage/oauth-private.key',
        ];
        
        foreach ($sensitivePatterns as $pattern) {
            if (str_contains($filePath, $pattern)) {
                $hook->response()->block("Cannot modify sensitive file: $filePath");
            }
        }
    }
}

// Allow all other operations
$hook->response()->continue();

Notification Handler Hook

Custom notification handling:

<?php

require 'vendor/autoload.php';

use BeyondCode\ClaudeHooks\ClaudeHook;
use BeyondCode\ClaudeHooks\Hooks\Notification;

$hook = ClaudeHook::create();

// Send to custom notification system
$notificationData = [
    'title' => $hook->title(),
    'message' => $hook->message(),
    'session' => $hook->sessionId(),
    'timestamp' => time()
];
    
// Send notification to Slack, Discord, etc.

$hook->success();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

beyondcode/claude-hooks-sdk 适用场景与选型建议

beyondcode/claude-hooks-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 989 次下载、GitHub Stars 达 66, 最近一次更新时间为 2025 年 07 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「hooks」 「beyondcode」 「claude」 「claude-hooks-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 beyondcode/claude-hooks-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 beyondcode/claude-hooks-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 beyondcode/claude-hooks-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 989
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 66
  • 点击次数: 6
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 66
  • Watchers: 1
  • Forks: 8
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-07-03