Token导航 LogoToken导航TokenDH.com
开发规范权限需确认github未标认证来源可访问clear审计未展示

laravel_documentation-best-practicesLaravel 文档最佳实践

Agent Skill

用于辅助文档、README、Markdown、说明文和内容稿件的整理与改写。它适合让 Agent 提炼结构、补齐章节、统一术语、检查链接或把零散材料整理成可读文档。使用时应保留项目已有事实、命令和路径,不要把未确认的信息写成确定结论;涉及对外文案时,还需要控制语气,避免过度营销或夸大能力。

总安装

1,382

周安装

57

GitHub Stars

公开资料未说明

下载量

451
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:laravel_documentation-best-practices(Laravel 文档最佳实践)
来源仓库:https://github.com/jpcaparas/superpowers-laravel
仓库路径:skills/laravel_documentation-best-practices
安装命令:
npx skills add jpcaparas/superpowers-laravel --skill "laravel:documentation-best-practices"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

AgentSkills.tonpx skills
npx skills add jpcaparas/superpowers-laravel --skill "laravel:documentation-best-practices"

简介

Laravel 文档最佳实践工具,用于优化 README 与项目说明文质量。

  • 适合在 AI 宿主中统一术语、补齐章节结构并提升可读性。
  • 通过 npx skills add 命令安装,输出应保留已有事实与命令准确性。
  • 涉及对外文案时需控制语气,避免夸大能力或承诺未经验证的功能。
  • laravel_documentation-best-practices 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Documentation Best Practices

Keep documentation minimal and meaningful. Well-written code with descriptive names often eliminates the need for comments. Document the "why" not the "what", and focus on complex business logic, not obvious code.

When NOT to Document

// BAD: Redundant comments that add no value
class UserController
{
    // This is the constructor
    public function __construct(
        // Inject user repository
        private UserRepository $repository
    ) {
        // Set the repository
        $this->repository = $repository;
    }

    // Get all users
    public function index()
    {
        // Return all users
        return $this->repository->all();
    }
}

// BAD: Obvious comments
$user->age = 25; // Set age to 25
$total = $price * $quantity; // Calculate total
if ($user->isActive()) { // Check if user is active
    // Send email
    $this->sendEmail($user);
}

When TO Document

1. Complex Business Logic

// GOOD: Explain complex business rules
class PricingCalculator
{
    /**
     * Calculate the final price with tiered discounts.
     *
     * Discount tiers:
     * - 10+ items: 5% discount
     * - 50+ items: 10% discount
     * - 100+ items: 15% discount
     * - VIP customers get additional 5% on top
     *
     * Note: Discounts don't apply to items already on sale
     */
    public function calculateTotal(Order $order): float
    {
        $subtotal = $order->items
            ->reject(fn($item) => $item->is_on_sale)
            ->sum(fn($item) => $item->price * $item->quantity);

        $regularItems = $order->items
            ->filter(fn($item) => !$item->is_on_sale);

        $discount = match(true) {
            $regularItems->sum('quantity') >= 100 => 0.15,
            $regularItems->sum('quantity') >= 50 => 0.10,
            $regularItems->sum('quantity') >= 10 => 0.05,
            default => 0
        };

        if ($order->customer->is_vip) {
            $discount += 0.05;
        }

        return $subtotal * (1 - $discount) + $this->calculateSaleItemsTotal($order);
    }
}

2. Non-Obvious Solutions

class QueryOptimizer
{
    /**
     * Using a subquery here instead of a join because it performs
     * 10x faster on large datasets (tested with 1M+ records).
     * The MySQL optimizer handles this pattern better with our indexes.
     */
    public function getActiveUsersWithRecentOrders()
    {
        return User::whereIn('id', function ($query) {
            $query->select('user_id')
                ->from('orders')
                ->where('created_at', '>', now()->subDays(30))
                ->groupBy('user_id');
        })->get();
    }

    /**
     * We're intentionally NOT eager loading relationships here.
     * The polymorphic relation combined with the large dataset
     * causes N+1 to actually be faster than the massive join.
     * Benchmarked: N+1 = 1.2s, Eager = 8.3s for 10k records.
     */
    public function getPolymorphicItems()
    {
        return Item::where('active', true)->get();
    }
}

3. Workarounds and Hacks

class PaymentGateway
{
    /**
     * WORKAROUND: Stripe's API has a bug where amounts over $999,999
     * cause a timeout. We split large transactions into multiple charges.
     * Remove this when Stripe fixes the issue (tracked in STRIPE-12345).
     */
    public function chargeLargeAmount(int $amountInCents): array
    {
        if ($amountInCents <= 99999900) {
            return [$this->charge($amountInCents)];
        }

        $charges = [];
        $remaining = $amountInCents;

        while ($remaining > 0) {
            $chargeAmount = min($remaining, 99999900);
            $charges[] = $this->charge($chargeAmount);
            $remaining -= $chargeAmount;
        }

        return $charges;
    }
}

4. External Dependencies and Integration Points

class ThirdPartyApiClient
{
    /**
     * Rate limit: 100 requests per minute (resets at minute boundary)
     * Docs: https://api.example.com/docs/rate-limits
     *
     * The API returns 429 with Retry-After header when limited.
     * We respect this header and queue retries accordingly.
     */
    public function makeRequest(string $endpoint, array $data = []): array
    {
        // Implementation
    }

    /**
     * The API expects dates in EST timezone regardless of server location.
     * All DateTime objects are converted to EST before sending.
     *
     * Known issue: DST transitions can cause 1-hour discrepancies.
     * The API team is aware but considers it low priority.
     */
    public function sendScheduledEvent(DateTime $scheduledAt, array $event): void
    {
        $scheduledAt->setTimezone(new DateTimeZone('America/New_York'));
        // ...
    }
}

Self-Documenting Code Techniques

1. Descriptive Naming

// BAD: Cryptic names require comments
public function calc($u, $i) // Calculate discount for user and items
{
    $d = 0; // discount
    if ($u->vip) { // if user is VIP
        $d = 0.1; // 10% discount
    }
    return $i * (1 - $d); // Apply discount
}

// GOOD: Self-explanatory names
public function calculateDiscountedPrice(User $customer, float $originalPrice): float
{
    $discountPercentage = $customer->is_vip ? 0.1 : 0;
    return $originalPrice * (1 - $discountPercentage);
}

2. Extract Methods for Clarity

// BAD: Complex condition needs explanation
if ($user->created_at > now()->subDays(7) &&
    $user->orders()->count() == 0 &&
    !$user->hasVerifiedEmail()) {
    // New unverified user without orders
    $this->sendWelcomeReminder($user);
}

// GOOD: Method name explains the condition
if ($this->isNewUnengagedUser($user)) {
    $this->sendWelcomeReminder($user);
}

private function isNewUnengagedUser(User $user): bool
{
    return $user->created_at > now()->subDays(7)
        && $user->orders()->count() == 0
        && !$user->hasVerifiedEmail();
}

3. Type Declarations and Return Types

// BAD: Unclear what the function accepts and returns
function process($data)
{
    // What is $data? What does this return?
}

// GOOD: Types make it self-documenting
function processOrderItems(Collection $items): OrderSummary
{
    // Clear input and output types
}

4. Value Objects for Domain Concepts

// BAD: What does this string represent?
public function setPrice(string $price)
{
    $this->price = $price;
}

// GOOD: Type clarifies the domain concept
public function setPrice(Money $price)
{
    $this->price = $price;
}

// The Money class documents the concept
class Money
{
    public function __construct(
        private int $cents,
        private string $currency = 'USD'
    ) {
        if ($cents < 0) {
            throw new InvalidArgumentException('Amount cannot be negative');
        }
    }

    public function formatted(): string
    {
        return number_format($this->cents / 100, 2);
    }
}

PHPDoc Best Practices

When to Use PHPDoc

/**
 * Process a refund for an order.
 *
 * @param Order $order The order to refund
 * @param float $amount Amount to refund (null for full refund)
 * @param string $reason Reason for the refund (for audit log)
 *
 * @throws PaymentGatewayException When payment gateway is unreachable
 * @throws InsufficientFundsException When refund amount exceeds paid amount
 * @throws RefundWindowExpiredException When refund window (90 days) has passed
 *
 * @return Refund The created refund record
 */
public function processRefund(
    Order $order,
    ?float $amount = null,
    string $reason = 'Customer request'
): Refund {
    // Complex refund logic
}

IDE Helper Annotations

class UserRepository
{
    /**
     * @return Collection<int, User>
     */
    public function getActiveUsers(): Collection
    {
        return User::where('active', true)->get();
    }

    /**
     * @param array<string, mixed> $filters
     * @return Builder<User>
     */
    public function applyFilters(array $filters): Builder
    {
        return User::query()->where($filters);
    }
}

Deprecation Notices

class PaymentService
{
    /**
     * @deprecated Since v2.0, use processPaymentWithStripe() instead
     * @see processPaymentWithStripe()
     */
    public function processPayment($amount)
    {
        trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
        return $this->processPaymentWithStripe($amount);
    }
}

API Documentation

1. Controller Method Documentation

class ApiController extends Controller
{
    /**
     * List all products with optional filtering.
     *
     * @group Products
     * @queryParam category string Filter by category slug. Example: electronics
     * @queryParam min_price number Minimum price filter. Example: 10.00
     * @queryParam max_price number Maximum price filter. Example: 100.00
     * @queryParam sort string Sort field (price, name, created_at). Default: name
     *
     * @response 200 {
     *   "data": [
     *     {
     *       "id": 1,
     *       "name": "Product Name",
     *       "price": "29.99",
     *       "category": "electronics"
     *     }
     *   ],
     *   "meta": {
     *     "total": 100,
     *     "per_page": 20,
     *     "current_page": 1
     *   }
     * }
     */
    public function index(Request $request)
    {
        // Implementation
    }
}

2. API Resource Documentation

/**
 * @property-read int $id
 * @property-read string $name
 * @property-read Money $price
 * @property-read Carbon $created_at
 * @property-read Category $category
 * @property-read Collection<int, Review> $reviews
 */
class ProductResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->price->formatted(),
            'category' => new CategoryResource($this->whenLoaded('category')),
            'reviews' => ReviewResource::collection($this->whenLoaded('reviews')),
            'created_at' => $this->created_at->toIso8601String(),
        ];
    }
}

README Documentation

Project README Template

# Project Name

Brief description of what this project does.

## Requirements

- PHP 8.2+
- MySQL 8.0+
- Redis 6.0+
- Node.js 18+

## Installation

\```bash
# Clone repository
git clone https://github.com/username/project.git
cd project

# Install dependencies
composer install
npm install

# Environment setup
cp .env.example .env
php artisan key:generate

# Database setup
php artisan migrate --seed

# Start development server
php artisan serve
\```

## Key Features

- Feature 1: Brief description
- Feature 2: Brief description
- Feature 3: Brief description

## Architecture Decisions

### Why We Use X Instead of Y

Brief explanation of important technical decisions.

### Database Design

Key points about the database structure.

## Testing

\```bash
# Run all tests
php artisan test

# Run specific test suite
php artisan test --testsuite=Feature

# With coverage
php artisan test --coverage
\```

## Deployment

Instructions for deploying to production.

## Troubleshooting

### Common Issue 1
Solution to common issue 1.

### Common Issue 2
Solution to common issue 2.

Configuration Documentation

// config/custom.php
return [
    /*
    |--------------------------------------------------------------------------
    | Cache TTL Settings
    |--------------------------------------------------------------------------
    |
    | These values determine how long various types of data are cached.
    | The values are in seconds. Shorter values mean fresher data but
    | more database queries. Adjust based on your needs.
    |
    */
    'cache_ttl' => [
        'short' => env('CACHE_TTL_SHORT', 60),      // User-specific data
        'medium' => env('CACHE_TTL_MEDIUM', 300),   // Frequently changing
        'long' => env('CACHE_TTL_LONG', 3600),      // Rarely changing
        'forever' => env('CACHE_TTL_FOREVER', 86400), // Static data
    ],

    /*
    |--------------------------------------------------------------------------
    | External API Configuration
    |--------------------------------------------------------------------------
    |
    | Configuration for third-party API integrations. Each service has
    | its own timeout and retry settings. Credentials are stored in .env
    |
    */
    'external_apis' => [
        'weather' => [
            'base_url' => env('WEATHER_API_URL', 'https://api.weather.com'),
            'timeout' => 5,  // seconds
            'retries' => 3,
            // Rate limit: 100 requests per minute
        ],
    ],
];

Migration Documentation

class CreateOrdersTable extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();

            // Customer reference - soft delete cascade handled in model
            $table->foreignId('user_id')->constrained();

            // Status uses enum for type safety (see App\Enums\OrderStatus)
            $table->string('status')->default('pending')->index();

            // Monetary values stored as integers (cents) to avoid float precision issues
            $table->unsignedInteger('subtotal');
            $table->unsignedInteger('tax');
            $table->unsignedInteger('total');

            // Snapshot shipping address as JSON for historical accuracy
            // even if customer updates their address later
            $table->json('shipping_address');

            // Soft deletes for audit trail
            $table->softDeletes();

            $table->timestamps();

            // Composite index for common query pattern
            $table->index(['user_id', 'status', 'created_at']);
        });
    }
}

Testing Documentation

test('document complex test scenarios', function () {
    /**
     * Scenario: Test that expired discount codes are rejected
     *
     * Given: A discount code that expired yesterday
     * When: User attempts to apply it to their cart
     * Then: The code should be rejected with appropriate message
     * And: The cart total should remain unchanged
     */

    $expiredCode = DiscountCode::factory()->expired()->create();
    $cart = Cart::factory()->withItems(3)->create();
    $originalTotal = $cart->total;

    $response = $this->postJson("/api/cart/{$cart->id}/discount", [
        'code' => $expiredCode->code,
    ]);

    $response->assertUnprocessable()
        ->assertJsonPath('errors.code.0', 'This discount code has expired.');

    expect($cart->fresh()->total)->toBe($originalTotal);
});

Best Practices Summary

  1. Code should be self-documenting through good naming
  2. Document WHY, not WHAT
  3. Keep comments close to the code they describe
  4. Update documentation when code changes
  5. Use tools to generate API documentation
  6. Document complex business rules thoroughly
  7. Include examples in documentation
  8. Document breaking changes clearly
  9. Keep README files up to date
  10. Document environmental dependencies

Remember: The best documentation is code that doesn't need documentation. Strive for clarity in your code first, then document what remains complex or non-obvious.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

29.64%
按下载量换算134

Antigravity

24.89%
按下载量换算112

OpenCode

16.25%
按下载量换算73

windsurf

12.29%
按下载量换算55

Gemini CLI

8.55%
按下载量换算39

Codex

3.33%
按下载量换算15

安全审计

暂无安全审计结果可展示。

权限和风险

权限需确认

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills