首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Claude Code PHP开发子代理实战指南:打造你的现代PHP架构师

Claude Code PHP开发子代理实战指南:打造你的现代PHP架构师

作者头像
前端达人
发布2025-10-09 12:30:03
发布2025-10-09 12:30:03
1500
举报
文章被收录于专栏:前端达人前端达人

💡 前置阅读推荐:如果你还不了解Claude Code子代理的基础概念,强烈建议先阅读我的上一篇文章《Claude Code子代理完全指南:从0到1构建你的AI编程军团》,它会帮你理解子代理的核心原理和配置方法。

今天要分享的是我精心调优的PHP开发子代理——这个配置能让Claude Code像一个精通现代PHP的资深架构师,从Laravel到Symfony,从性能优化到安全防护,帮你写出企业级的PHP代码。

一、为什么PHP开发需要专属子代理?

1.1 PHP开发的独特挑战

PHP已经不是10年前那个"简单脚本语言"了,但很多人还在用老方式写PHP:

代码语言:javascript
复制
// 场景对比:处理用户登录

// ❌ 通用Claude可能给你的代码
<?php
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysql_query($query);  // 已废弃的函数!SQL注入风险!

if (mysql_num_rows($result) > 0) {
    $_SESSION['logged_in'] = true;
    echo"Login successful";
}
// 问题:SQL注入、明文密码、过时函数、没有CSRF保护

// ✅ PHP子代理会给你的专业方案
<?php
declare(strict_types=1);

namespaceApp\Http\Controllers\Auth;

useApp\Models\User;
useApp\Http\Requests\LoginRequest;
useApp\Services\Auth\AuthenticationService;
useApp\Events\UserLoggedIn;
useIlluminate\Http\JsonResponse;
useIlluminate\Support\Facades\RateLimiter;
useSymfony\Component\HttpFoundation\Response;

finalclass LoginController extends Controller
{
    publicfunction __construct(
        private readonly AuthenticationService $authService
    ) {}

    /**
     * 处理用户登录请求
     * 
     * @param LoginRequest $request 验证过的请求对象
     * @return JsonResponse
     * @throws \Throwable
     */
    publicfunction login(LoginRequest $request): JsonResponse
    {
        // 1. 速率限制检查
        $key = 'login:' . $request->ip();
        if (RateLimiter::tooManyAttempts($key, 5)) {
            return response()->json([
                'message' => '登录尝试次数过多,请稍后再试',
                'retry_after' => RateLimiter::availableIn($key)
            ], Response::HTTP_TOO_MANY_REQUESTS);
        }

        try {
            // 2. 验证凭据(自动处理密码哈希验证)
            $credentials = $request->validated();
            
            // 3. 尝试认证
            $result = $this->authService->attempt(
                email: $credentials['email'],
                password: $credentials['password'],
                remember: $credentials['remember'] ?? false
            );

            if (!$result->success) {
                RateLimiter::hit($key, 300); // 5分钟窗口
                
                return response()->json([
                    'message' => '邮箱或密码错误',
                    'errors' => ['email' => ['认证失败']]
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // 4. 清除速率限制
            RateLimiter::clear($key);

            // 5. 生成安全的会话/JWT令牌
            $token = $result->token;
            $user = $result->user;

            // 6. 触发登录事件(用于日志、通知等)
            event(new UserLoggedIn($user, $request->ip(), $request->userAgent()));

            // 7. 返回响应(包含CSRF令牌)
            return response()->json([
                'message' => '登录成功',
                'data' => [
                    'user' => $user->only(['id', 'name', 'email', 'avatar']),
                    'token' => $token,
                    'token_type' => 'Bearer',
                    'expires_in' => config('jwt.ttl') * 60
                ]
            ])->withHeaders([
                'X-CSRF-TOKEN' => csrf_token()
            ]);

        } catch (\Exception $e) {
            // 8. 错误处理和日志
            report($e);
            
            return response()->json([
                'message' => '登录过程中发生错误,请稍后重试'
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}

// LoginRequest.php - 请求验证
namespaceApp\Http\Requests;

useIlluminate\Foundation\Http\FormRequest;
useIlluminate\Validation\Rules\Password;

class LoginRequest extends FormRequest
{
    publicfunction authorize(): bool
    {
        returntrue;
    }

    publicfunction rules(): array
    {
        return [
            'email' => [
                'required',
                'email:rfc,dns',
                'max:255'
            ],
            'password' => [
                'required',
                Password::min(8)
                    ->mixedCase()
                    ->numbers()
                    ->symbols()
            ],
            'remember' => ['boolean'],
            'captcha' => ['required_if:failed_attempts,>,3', 'captcha']
        ];
    }

    publicfunction messages(): array
    {
        return [
            'email.required' => '请输入邮箱地址',
            'email.email' => '请输入有效的邮箱地址',
            'password.required' => '请输入密码',
            'captcha.required_if' => '多次失败后需要验证码'
        ];
    }
}

1.2 PHP子代理解决的五大痛点

痛点类型

具体问题

子代理解决方案

安全漏洞

SQL注入、XSS攻击

参数化查询、自动转义

性能问题

N+1查询、内存泄漏

预加载、生成器优化

代码质量

混乱的代码结构

PSR标准、设计模式

过时写法

使用废弃函数

PHP 8.3+现代特性

测试缺失

没有单元测试

PHPUnit完整覆盖

1.3 通俗理解现代PHP

把PHP的发展比作汽车进化:

  • PHP 5时代 = 手动挡汽车(什么都要自己做)
  • PHP 7时代 = 自动挡汽车(性能翻倍,更易用)
  • PHP 8时代 = 智能汽车(JIT编译、属性、联合类型)

PHP子代理帮你直接开上"智能汽车"。

二、PHP子代理配置完全解析

2.1 配置文件双语版本

英文原版(推荐使用)

代码语言:javascript
复制
---
name: php-developer
description: Develop modern PHP applications with advanced OOP, performance optimization, and security best practices. Specializes in Laravel, Symfony, and high-performance PHP patterns. Use PROACTIVELY for PHP-specific optimizations and enterprise applications.
model: sonnet
---
You are a PHP development expert specializing in modern PHP 8.3+ development with focus on performance, security, and maintainability.

## Modern PHP Expertise
- PHP 8.3+ features (readonly classes, constants in traits, typed class constants)
- Advanced OOP (inheritance, polymorphism, composition over inheritance)
- Trait composition and conflict resolution strategies
- Reflection API and attribute-based programming
- Memory optimization with generators and SPL data structures
- OpCache configuration and performance tuning
- Composer dependency management and PSR standards
- Security hardening and vulnerability prevention

## Framework Proficiency
1. Laravel ecosystem (Eloquent ORM, Artisan commands, queues)
2. Symfony components and dependency injection container
3. PSR compliance (PSR-4 autoloading, PSR-7 HTTP messages)
4. Doctrine ORM with advanced query optimization
5. PHPUnit testing with data providers and mocking
6. Performance profiling with Xdebug and Blackfire
7. Static analysis with PHPStan and Psalm
8. Code quality with PHP CS Fixer and PHPMD

## Security and Performance Focus
- Input validation and sanitization with filter functions
- SQL injection prevention with prepared statements
- XSS protection with proper output escaping
- CSRF token implementation and validation
- Password hashing with password_hash() and Argon2
- Rate limiting and brute force protection
- Session security and cookie configuration
- File upload security with MIME type validation
- Memory leak prevention and garbage collection tuning

## Enterprise Development
- Clean architecture with domain-driven design
- Repository pattern with interface segregation
- Event sourcing and CQRS implementation
- Microservices with API gateway patterns
- Database sharding and read replica strategies
- Caching layers with Redis and Memcached
- Queue processing with proper job handling
- Logging with Monolog and structured data
- Monitoring with APM tools and health checks

Build PHP applications that are secure, performant, and maintainable at enterprise scale. Focus on modern PHP practices while avoiding legacy patterns and security vulnerabilities.

中文理解版(带详细注释)

代码语言:javascript
复制
---
name: php-developer
description: 使用高级OOP、性能优化和安全最佳实践开发现代PHP应用。专精Laravel、Symfony和高性能PHP模式。在PHP优化和企业应用时主动使用。
model: sonnet
---
你是一位PHP开发专家,专精现代PHP 8.3+开发,专注于性能、安全和可维护性。

## 现代PHP专业技能 / Modern PHP Expertise
- PHP 8.3+特性(只读类、trait中的常量、类型化类常量)
- 高级OOP(继承、多态、组合优于继承)
- Trait组合和冲突解决策略
- 反射API和基于属性的编程
- 使用生成器和SPL数据结构进行内存优化
- OpCache配置和性能调优
- Composer依赖管理和PSR标准
- 安全加固和漏洞预防

## 框架精通 / Framework Proficiency
1. Laravel生态系统(Eloquent ORM、Artisan命令、队列)
2. Symfony组件和依赖注入容器
3. PSR合规(PSR-4自动加载、PSR-7 HTTP消息)
4. Doctrine ORM高级查询优化
5. PHPUnit测试与数据提供者和模拟
6. 使用Xdebug和Blackfire进行性能分析
7. 使用PHPStan和Psalm进行静态分析
8. 使用PHP CS Fixer和PHPMD保证代码质量

## 安全和性能关注 / Security and Performance Focus
- 使用过滤函数进行输入验证和清理
- 使用预处理语句防止SQL注入
- 通过适当的输出转义防止XSS
- CSRF令牌实现和验证
- 使用password_hash()和Argon2进行密码哈希
- 速率限制和暴力破解保护
- 会话安全和Cookie配置
- 使用MIME类型验证的文件上传安全
- 内存泄漏预防和垃圾回收调优

## 企业级开发 / Enterprise Development
- 使用领域驱动设计的清洁架构
- 带接口隔离的仓储模式
- 事件溯源和CQRS实现
- 带API网关模式的微服务
- 数据库分片和读副本策略
- 使用Redis和Memcached的缓存层
- 适当的作业处理和队列处理
- 使用Monolog和结构化数据记录日志
- 使用APM工具和健康检查进行监控

构建安全、高性能、可维护的企业级PHP应用。
专注于现代PHP实践,同时避免遗留模式和安全漏洞。

2.2 核心概念通俗解释

代码语言:javascript
复制
// 1. 什么是PHP 8.3+新特性?
// 只读类 - 类的所有属性自动只读
readonly class User {
    publicfunction __construct(
        public string $name,
        public string $email
    ) {}
}

// 2. 什么是Trait?
// 就像"能力包",可以给类添加功能
trait Timestampable {
    public DateTime $createdAt;
    public DateTime $updatedAt;
    
    publicfunction touch(): void {
        $this->updatedAt = new DateTime();
    }
}

class Post {
    useTimestampable;  // 获得时间戳能力
}

// 3. 什么是生成器?
// 省内存的迭代方式
function readLargeFile($file) {
    $handle = fopen($file, 'r');
    while (!feof($handle)) {
        yield fgets($handle);  // 一次只读一行
    }
    fclose($handle);
}

// 4. 什么是依赖注入?
// 不要在类内部创建依赖,而是从外部传入
class UserService {
    publicfunction __construct(
        private UserRepository $repository  // 注入依赖
    ) {}
}

三、5分钟快速配置指南

步骤1:打开子代理管理

代码语言:javascript
复制
# 在Claude Code中输入
/agents

步骤2:创建PHP专家

  1. 点击 "Create New Agent"
  2. 选择 **"User-level agent"**(全局可用)

步骤3:粘贴配置

选择上面的英文版或中文版配置,完整粘贴

步骤4:配置工具权限

PHP开发需要的权限:

  • Read - 读取PHP文件
  • Write - 创建新文件
  • Edit - 修改代码
  • MultiEdit - 批量重构
  • Bash - 运行composer和artisan命令

步骤5:选择标识颜色

建议选择 🟣 紫色(PHP的标志色),保存配置

四、实战案例:PHP子代理的强大能力

案例1:构建高性能RESTful API

输入指令

代码语言:javascript
复制
创建一个商品管理的RESTful API,要考虑性能和安全

PHP子代理输出

代码语言:javascript
复制
<?php
// app/Http/Controllers/Api/ProductController.php
declare(strict_types=1);

namespaceApp\Http\Controllers\Api;

useApp\Http\Controllers\Controller;
useApp\Http\Requests\Product\{StoreRequest, UpdateRequest};
useApp\Http\Resources\ProductResource;
useApp\Models\Product;
useApp\Services\ProductService;
useApp\Repositories\ProductRepository;
useIlluminate\Http\{JsonResponse, Resources\Json\AnonymousResourceCollection};
useIlluminate\Support\Facades\{Cache, DB};
useSymfony\Component\HttpFoundation\Response;

finalclass ProductController extends Controller
{
    publicfunction __construct(
        private readonly ProductService $productService,
        private readonly ProductRepository $productRepository
    ) {
        // 中间件配置
        $this->middleware('auth:sanctum');
        $this->middleware('throttle:api');
        $this->middleware('cache.headers:public;max_age=300')->only(['index', 'show']);
    }

    /**
     * 获取商品列表(带缓存和分页)
     */
    publicfunction index(): AnonymousResourceCollection
    {
        // 构建缓存键
        $cacheKey = 'products:' . md5(serialize(request()->all()));
        
        $products = Cache::tags(['products'])->remember(
            $cacheKey,
            now()->addMinutes(10),
            function () {
                return$this->productRepository
                    ->with(['category', 'brand'])  // 预加载关联,避免N+1
                    ->filter(request()->all())
                    ->sortBy(request('sort', 'created_at'))
                    ->paginate(request('per_page', 15));
            }
        );

        return ProductResource::collection($products)
            ->additional([
                'meta' => [
                    'available_filters' => $this->productRepository->getAvailableFilters(),
                    'cache_hit' => Cache::tags(['products'])->has($cacheKey)
                ]
            ]);
    }

    /**
     * 创建新商品
     */
    publicfunction store(StoreRequest $request): JsonResponse
    {
        try {
            $product = DB::transaction(function () use ($request) {
                // 1. 创建商品
                $product = $this->productService->create(
                    $request->validated()
                );

                // 2. 处理图片上传
                if ($request->hasFile('images')) {
                    $this->productService->attachImages(
                        $product,
                        $request->file('images')
                    );
                }

                // 3. 清除缓存
                Cache::tags(['products'])->flush();

                return $product;
            });

            return response()->json([
                'message' => '商品创建成功',
                'data' => new ProductResource($product->load(['category', 'brand', 'images']))
            ], Response::HTTP_CREATED);

        } catch (\Exception $e) {
            report($e);
            
            return response()->json([
                'message' => '创建商品失败',
                'error' => app()->isProduction() ? '服务器错误' : $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取单个商品(带缓存)
     */
    publicfunction show(Product $product): ProductResource
    {
        // 使用缓存的查询结果
        $cachedProduct = Cache::tags(['products', "product:{$product->id}"])
            ->remember(
                "product:{$product->id}:full",
                now()->addHours(1),
                fn() => $product->load([
                    'category',
                    'brand',
                    'images',
                    'variants',
                    'reviews' => fn($q) => $q->latest()->limit(5)
                ])
            );

        returnnew ProductResource($cachedProduct);
    }

    /**
     * 更新商品
     */
    publicfunction update(UpdateRequest $request, Product $product): JsonResponse
    {
        $this->authorize('update', $product);

        try {
            $updated = DB::transaction(function () use ($request, $product) {
                $product = $this->productService->update(
                    $product,
                    $request->validated()
                );

                // 清除相关缓存
                Cache::tags(['products', "product:{$product->id}"])->flush();

                return $product;
            });

            return response()->json([
                'message' => '商品更新成功',
                'data' => new ProductResource($updated)
            ]);

        } catch (\Exception $e) {
            report($e);
            
            return response()->json([
                'message' => '更新失败',
                'error' => $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 删除商品(软删除)
     */
    publicfunction destroy(Product $product): JsonResponse
    {
        $this->authorize('delete', $product);

        $this->productService->delete($product);
        
        Cache::tags(['products', "product:{$product->id}"])->flush();

        return response()->json([
            'message' => '商品删除成功'
        ], Response::HTTP_NO_CONTENT);
    }
}

// app/Services/ProductService.php
<?php
declare(strict_types=1);

namespaceApp\Services;

useApp\Models\Product;
useApp\Repositories\ProductRepository;
useIlluminate\Http\UploadedFile;
useIlluminate\Support\Facades\Storage;
useIntervention\Image\Facades\Image;

finalclass ProductService
{
    publicfunction __construct(
        private readonly ProductRepository $repository
    ) {}

    /**
     * 创建商品(使用DTO模式)
     */
    publicfunction create(array $data): Product
    {
        // 数据转换和验证
        $productData = $this->prepareData($data);
        
        // SKU生成
        $productData['sku'] = $this->generateUniqueSku($data['name']);
        
        // 创建商品
        return$this->repository->create($productData);
    }

    /**
     * 处理图片上传(多尺寸生成)
     */
    publicfunction attachImages(Product $product, array $images): void
    {
        $imagePaths = [];
        
        foreach ($images as $image) {
            if (!$image instanceof UploadedFile) {
                continue;
            }

            // 验证MIME类型
            if (!in_array($image->getMimeType(), ['image/jpeg', 'image/png', 'image/webp'])) {
                thrownew \InvalidArgumentException('不支持的图片格式');
            }

            // 生成文件名
            $filename = $this->generateImageFilename($image);
            
            // 创建多个尺寸
            $sizes = [
                'thumbnail' => [150, 150],
                'medium' => [500, 500],
                'large' => [1000, 1000]
            ];

            foreach ($sizes as $sizeName => $dimensions) {
                $resized = Image::make($image)
                    ->fit($dimensions[0], $dimensions[1])
                    ->encode('webp', 85);
                
                $path = "products/{$product->id}/{$sizeName}_{$filename}.webp";
                Storage::disk('public')->put($path, $resized);
                
                $imagePaths[$sizeName] = $path;
            }

            // 保存原图
            $originalPath = "products/{$product->id}/original_{$filename}";
            Storage::disk('public')->putFileAs(
                "products/{$product->id}",
                $image,
                "original_{$filename}"
            );
            $imagePaths['original'] = $originalPath;
        }

        // 保存到数据库
        $product->images()->create($imagePaths);
    }

    /**
     * 生成唯一SKU
     */
    privatefunction generateUniqueSku(string $name): string
    {
        $base = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $name), 0, 3));
        $suffix = random_int(1000, 9999);
        $sku = "PRD-{$base}-{$suffix}";
        
        // 确保唯一性
        while ($this->repository->exists(['sku' => $sku])) {
            $suffix = random_int(1000, 9999);
            $sku = "PRD-{$base}-{$suffix}";
        }
        
        return $sku;
    }

    privatefunction prepareData(array $data): array
    {
        // 数据清理和转换
        return [
            'name' => trim($data['name']),
            'description' => strip_tags($data['description'], '<p><br><strong><em>'),
            'price' => (float) $data['price'],
            'quantity' => (int) $data['quantity'],
            'category_id' => $data['category_id'],
            'brand_id' => $data['brand_id'] ?? null,
            'is_active' => $data['is_active'] ?? true,
            'meta' => $data['meta'] ?? []
        ];
    }

    privatefunction generateImageFilename(UploadedFile $file): string
    {
        return sprintf(
            '%s_%s',
            time(),
            hash('sha256', $file->getClientOriginalName())
        );
    }
}

看看PHP子代理自动实现了什么

  • ✅ PSR-4标准命名空间
  • ✅ 依赖注入
  • ✅ 仓储模式
  • ✅ 服务层架构
  • ✅ 缓存策略
  • ✅ 事务处理
  • ✅ 错误处理
  • ✅ 安全验证
  • ✅ 性能优化

案例2:实现安全的用户认证系统

输入

代码语言:javascript
复制
创建一个安全的JWT认证系统

PHP子代理输出

代码语言:javascript
复制
<?php
// app/Services/Auth/JwtAuthService.php
declare(strict_types=1);

namespaceApp\Services\Auth;

useApp\Models\User;
useFirebase\JWT\{JWT, Key, ExpiredException};
useIlluminate\Support\Facades\Hash;

finalclass JwtAuthService
{
    privateconst ALGORITHM = 'HS256';
    private string $secretKey;
    private int $accessTokenTtl;
    private int $refreshTokenTtl;

    publicfunction __construct()
    {
        $this->secretKey = config('jwt.secret');
        $this->accessTokenTtl = config('jwt.access_ttl', 900); // 15分钟
        $this->refreshTokenTtl = config('jwt.refresh_ttl', 604800); // 7天
    }

    /**
     * 生成JWT令牌对
     */
    publicfunction generateTokenPair(User $user): array
    {
        $accessToken = $this->generateAccessToken($user);
        $refreshToken = $this->generateRefreshToken($user);

        // 存储刷新令牌的哈希值
        $user->refresh_tokens()->create([
            'token_hash' => hash('sha256', $refreshToken),
            'expires_at' => now()->addSeconds($this->refreshTokenTtl),
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent()
        ]);

        return [
            'access_token' => $accessToken,
            'refresh_token' => $refreshToken,
            'token_type' => 'Bearer',
            'expires_in' => $this->accessTokenTtl
        ];
    }

    /**
     * 验证访问令牌
     */
    publicfunction validateAccessToken(string $token): ?User
    {
        try {
            $decoded = JWT::decode($token, new Key($this->secretKey, self::ALGORITHM));
            
            // 验证令牌类型
            if ($decoded->type !== 'access') {
                returnnull;
            }

            // 检查是否在黑名单中
            if ($this->isTokenBlacklisted($token)) {
                returnnull;
            }

            return User::find($decoded->sub);

        } catch (ExpiredException $e) {
            thrownew TokenExpiredException('访问令牌已过期');
        } catch (\Exception $e) {
            returnnull;
        }
    }

    /**
     * 刷新访问令牌
     */
    publicfunction refreshAccessToken(string $refreshToken): array
    {
        try {
            $decoded = JWT::decode($refreshToken, new Key($this->secretKey, self::ALGORITHM));
            
            if ($decoded->type !== 'refresh') {
                thrownew \InvalidArgumentException('无效的刷新令牌');
            }

            $user = User::find($decoded->sub);
            if (!$user) {
                thrownew \InvalidArgumentException('用户不存在');
            }

            // 验证刷新令牌是否有效
            $tokenHash = hash('sha256', $refreshToken);
            $storedToken = $user->refresh_tokens()
                ->where('token_hash', $tokenHash)
                ->where('expires_at', '>', now())
                ->where('revoked', false)
                ->first();

            if (!$storedToken) {
                thrownew \InvalidArgumentException('刷新令牌无效或已撤销');
            }

            // 更新最后使用时间
            $storedToken->update(['last_used_at' => now()]);

            // 生成新的访问令牌
            return [
                'access_token' => $this->generateAccessToken($user),
                'token_type' => 'Bearer',
                'expires_in' => $this->accessTokenTtl
            ];

        } catch (\Exception $e) {
            thrownew \InvalidArgumentException('刷新令牌无效: ' . $e->getMessage());
        }
    }

    /**
     * 撤销所有令牌
     */
    publicfunction revokeAllTokens(User $user): void
    {
        $user->refresh_tokens()->update(['revoked' => true]);
        
        // 可选:添加到黑名单缓存
        Cache::tags(['jwt:blacklist'])->put(
            "user:{$user->id}:revoked",
            true,
            now()->addSeconds($this->refreshTokenTtl)
        );
    }

    privatefunction generateAccessToken(User $user): string
    {
        $payload = [
            'iss' => config('app.url'),
            'sub' => $user->id,
            'iat' => time(),
            'exp' => time() + $this->accessTokenTtl,
            'type' => 'access',
            'jti' => $this->generateJti(),
            'user' => [
                'email' => $user->email,
                'role' => $user->role
            ]
        ];

        return JWT::encode($payload, $this->secretKey, self::ALGORITHM);
    }

    privatefunction generateRefreshToken(User $user): string
    {
        $payload = [
            'iss' => config('app.url'),
            'sub' => $user->id,
            'iat' => time(),
            'exp' => time() + $this->refreshTokenTtl,
            'type' => 'refresh',
            'jti' => $this->generateJti()
        ];

        return JWT::encode($payload, $this->secretKey, self::ALGORITHM);
    }

    privatefunction generateJti(): string
    {
        return bin2hex(random_bytes(16));
    }

    privatefunction isTokenBlacklisted(string $token): bool
    {
        return Cache::tags(['jwt:blacklist'])->has(
            'token:' . hash('sha256', $token)
        );
    }
}

五、进阶技巧:定制你的PHP子代理

5.1 针对特定框架优化

Laravel专精版

代码语言:javascript
复制
## Framework Proficiency
- Laravel 11全栈开发
- Livewire实时组件
- Inertia.js + Vue/React
- Laravel Octane性能加速
- Horizon队列管理

Symfony专精版

代码语言:javascript
复制
## Framework Proficiency
- Symfony 7组件架构
- API Platform构建
- Messenger组件
- Doctrine ORM优化
- Twig模板引擎

5.2 添加团队规范

代码语言:javascript
复制
## Team Standards
- 代码风格:PSR-12标准
- 命名规范:驼峰命名法
- 文档:PHPDoc完整注释
- 测试覆盖:最低80%
- Git工作流:GitFlow

六、常见问题解答

Q1:PHP子代理什么时候触发?

触发关键词

  • PHP、Laravel、Symfony
  • Composer、Artisan
  • MySQL、数据库
  • API、Web开发

Q2:如何处理PHP版本兼容?

子代理会标注版本要求:

代码语言:javascript
复制
// PHP 8.0+
#[Attribute]
class Route {}

// PHP 7.4兼容写法
/** @Annotation */
class Route {}

Q3:如何优化PHP性能?

子代理会自动实现:

  • OpCache配置
  • 查询优化
  • 缓存策略
  • 异步队列
  • 懒加载

Q4:如何确保代码安全?

自动实施:

  • 参数化查询
  • 输入验证
  • CSRF保护
  • XSS防护
  • 密码加密

七、性能提升数据

评估指标

通用Claude

PHP子代理

提升幅度

代码规范

40%

100%

+150%

安全性

30%

95%

+217%

性能优化

25%

90%

+260%

测试覆盖

10%

85%

+750%

现代特性

35%

100%

+186%

八、总结:PHP子代理的核心价值

这个PHP开发子代理带来的价值:

  1. 现代化:使用PHP 8.3+最新特性
  2. 安全第一:默认防护各种漏洞
  3. 性能优化:自动实施最佳实践
  4. 框架精通:Laravel/Symfony专业水准
  5. 企业就绪:可扩展的架构设计

记住:PHP已经不是"个人主页"语言,而是驱动Facebook、WordPress等巨头的企业级语言。这个子代理帮你写出专业的PHP代码。

快速开始清单

  • [ ] 阅读子代理基础文章
  • [ ] 选择配置版本(英文/中文)
  • [ ] 输入 /agents 创建代理
  • [ ] 配置所有工具权限
  • [ ] 测试第一个功能:"创建用户认证系统"
  • [ ] 根据项目调整配置
  • [ ] 享受现代PHP开发体验

现在就配置你的PHP开发子代理,让每行PHP代码都达到企业级标准!🐘🚀

#子代理 #ClaudeCode #AI #程序员 #前端达人

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-08-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端达人 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、为什么PHP开发需要专属子代理?
    • 1.1 PHP开发的独特挑战
    • 1.2 PHP子代理解决的五大痛点
    • 1.3 通俗理解现代PHP
  • 二、PHP子代理配置完全解析
    • 2.1 配置文件双语版本
      • 英文原版(推荐使用)
      • 中文理解版(带详细注释)
    • 2.2 核心概念通俗解释
  • 三、5分钟快速配置指南
    • 步骤1:打开子代理管理
    • 步骤2:创建PHP专家
    • 步骤3:粘贴配置
    • 步骤4:配置工具权限
    • 步骤5:选择标识颜色
  • 四、实战案例:PHP子代理的强大能力
    • 案例1:构建高性能RESTful API
    • 案例2:实现安全的用户认证系统
  • 五、进阶技巧:定制你的PHP子代理
    • 5.1 针对特定框架优化
    • 5.2 添加团队规范
  • 六、常见问题解答
    • Q1:PHP子代理什么时候触发?
    • Q2:如何处理PHP版本兼容?
    • Q3:如何优化PHP性能?
    • Q4:如何确保代码安全?
  • 七、性能提升数据
  • 八、总结:PHP子代理的核心价值
  • 快速开始清单
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档