metalogico/laravel-mocka
Composer 安装命令:
composer require --dev metalogico/laravel-mocka
包简介
Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic
README 文档
README
Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic.
Why Mocka?
When your Laravel app calls external APIs (like DMS, MES, or any third-party service), you often need to provide mock responses for:
- 🍎 App Store Reviews - Apple and Google reviewers need working apps without real API access
- 🧪 Testing Environments - Stable, predictable responses for your test suite
- 👥 Demo Users - Showcase your app without depending on external services
- 🚀 Development - Work offline or with unstable external APIs
Features
- 🎯 User-specific mocking - Mock responses only for designated users
- 🔄 Drop-in replacement - Use
MockaHttpinstead of Laravel'sHttpfacade - 📁 File-based mocks - Organize mock responses in PHP files
- 🎨 Response templating - Dynamic mock responses with Faker integration
- 📊 Request logging - Track which requests are mocked vs real
- ❌ Error simulation - Test failure scenarios easily
- 🛣️ Header activator - Enable/disable mocking via
X-Mockaheader - 📝 Force activation - Enable/disable mocking via
withOptions(['mocka' => true]) - 🐌 Rate limiting simulation - Simulate slow APIs delays for testing
- 🔍 Advanced URL matching - Regex, wildcards, and parameter matching (coming soon ™)
- ⌘ Command Line tools - List mappings
- ⚡ Zero performance impact - Only active for designated users
Installation
You can install the package via composer:
composer require metalogico/laravel-mocka
Publish the config file:
php artisan vendor:publish --tag="mocka-config"
Quick Start
1. Configure Mock Users
In your .env file:
MOCKA_ENABLED=true MOCKA_USERS=reviewer@apple.com,tester@google.com,demo@yourapp.com MOCKA_LOGS=true
2. Create Mock Files
Create mock files in resources/mocka/:
resources/mocka/api.mock.php
<?php return [ 'POST' => [ 'authenticate' => [ 'success' => true, 'user_id' => 12345, 'token' => 'mock_token_12345', 'expires_at' => time() + 3600, ], ], 'GET' => [ 'getFileList' => [ 'success' => true, 'files' => [ [ 'name' => 'file1.pdf', 'size' => 1024, 'created_at' => '2023-01-01 00:00:00', ], [ 'name' => 'file2.pdf', 'size' => 2048, 'created_at' => '2023-01-02 00:00:00', ], // ... ], ] ], ];
3. Configure URL Mappings
In config/mocka.php:
'mappings' => [ [ 'url' => env('EXTERNAL_API_URL').'/api/authenticate', 'file' => 'api.mock.php', 'key' => 'POST.authenticate', ], [ 'url' => env('EXTERNAL_API_URL').'/api/files/', 'file' => 'api.mock.php', 'key' => 'GET.getFileList', ], ];
4. Use MockaHttp in Your Services
Replace Laravel's Http facade with MockaHttp:
<?php namespace App\Services; use Metalogico\Mocka\Facades\MockaHttp; class DmsService { public static function authenticate($user, $password) { $response = MockaHttp::post(config('external_api_url').'/api/authenticate', [ 'user' => $user, 'password' => $password, ]); session()->put('token', $response->json()['token']); return $response->json(); } public static function getFileList() { $response = MockaHttp::withHeaders([ 'Authorization' => 'Bearer '.session()->get('token'), ])->get(config('external_api_url').'/api/files'); return $response->json(); } }
Advanced Features
Response Types: Static, Dynamic, or Hybrid
Mocka supports three approaches for mock responses:
Static Responses
Perfect for app store reviews and basic demos:
return [ 'GET' => [ 'simpleAuth' => [ 'success' => true, 'token' => 'static_token_123', 'user_id' => 12345, ], ], ];
Dynamic Responses
For complex testing with varying data:
return [ 'GET' => [ 'userList' => fn() => [ 'users' => collect(range(1, fake()->numberBetween(3, 8))) ->map(fn() => [ 'name' => fake()->name, 'email' => fake()->email, ]), 'total' => fake()->numberBetween(50, 200), ], ], ], ];
Hybrid Responses
You can even mix static and dynamic data as needed:
return [ 'GET' => [ 'mixedResponse' => fn() => [ 'status' => 'success', // Static 'timestamp' => time(), // Static but with function 'dynamic_data' => fn() => [ 'user_count' => fake()->numberBetween(5, 20), 'featured_products' => collect(range(1, 3)) ->map(fn() => [ 'id' => fake()->numberBetween(1000, 9999), 'name' => fake()->words(3, true), 'price' => fake()->randomFloat(2, 10, 500), ]), ], ], ], ], ];
Advanced URL Matching
Configure sophisticated URL matching patterns:
'mappings' => [ // Exact match [ 'url' => 'https://api.example.com/users/123', 'match' => 'exact', // which is the default 'file' => 'users.mock.php', 'key' => 'GET.specificUser', ], // Wildcard matching [ 'url' => 'https://api.example.com/users/*', 'match' => 'wildcard', 'file' => 'users.mock.php', 'key' => 'GET.anyUser', ], // Regex matching (coming soon ™) [ 'url' => '/^https:\/\/api\.example\.com\/orders\/\d+$/', 'match' => 'regex', 'file' => 'orders.mock.php', 'key' => 'GET.orderDetail', ], ];
Error Simulation
Simulate API errors by defining error configurations in your mappings:
'mappings' => [ [ 'url' => 'https://api.example.com/users/123', 'file' => 'users.mock.php', 'key' => 'GET.specificUser', 'errors' => 'GET.specificUserErrors' // Optional error configuration ], ];
Define error responses in your mock files:
return [ 'GET' => [ 'specificUser' => fn() => [ 'id' => fake()->numberBetween(1000, 9999), 'name' => fake()->name, 'email' => fake()->email, ], 'specificUserErrors' => [ 'error_rate' => 25, // 25% chance of error 'errors' => [ 422 => [ 'message' => 'Validation failed', 'errors' => ['name' => ['Name is required']] ], 404 => [ 'message' => 'User not found', 'code' => 'USER_NOT_FOUND', 'timestamp' => time() ], 503 => fn() => [ // Dynamic error responses 'message' => 'Service temporarily unavailable', 'retry_after' => fake()->numberBetween(30, 300), 'incident_id' => fake()->uuid, ], ], ], ], ];
Rate Limiting Simulation
Add delays to simulate slow APIs:
'mappings' => [ [ 'url' => 'https://slow-api.com/data', 'file' => 'slow.mock.php', 'key' => 'GET.slowResponse', 'delay' => 5000, // 5 second delay ], ];
Jobs and Artisan (Force Activation)
When running inside queued Jobs or Artisan commands (where there is no web request/user), you can explicitly enable Mocka per request using options:
use Metalogico\Mocka\Facades\MockaHttp; $enabled = ($user === 'reviewer@apple.com') ? true : false; $response = MockaHttp::withOptions(['mocka' => $enabled]) ->get(config('external_api_url').'/api/files');
Notes:
- Mocka must still be enabled and allowed in the current environment/host by config.
- If the current user is in
MOCKA_USERS, forcing is not required (it's always active). - You can also use the
X-Mockaheader in regular request contexts to activate per-call.
Artisan Commands
List Mock Mappings
List all configured mappings and whether they correctly resolve to a mock file/key. The output uses a compact, two-line layout per mapping:
php artisan mocka:list
Per mapping you will see two rows:
- Main row — shows mapping details and overall Status for file/key resolution.
- Sub-row — shows the
errorskey (or-if none) in thekeycolumn, and its validation result instatus.
Configuration
The configuration file config/mocka.php supports these options:
return [ // Globally enable Mocka (default: false in production) 'enabled' => env('MOCKA_ENABLED', false), // Basic logging (can be extended later) 'logs' => env('MOCKA_LOGS', false), // Users (emails) for which Mocka is active when enabled // Supports comma-separated env var: MOCKA_USERS="apple@example.com, foo@bar.com" 'users' => array_values(array_filter(array_map('trim', explode(',', env('MOCKA_USERS', ''))))), // Path to mock files 'mocks_path' => resource_path('mocka'), // Default delay for all mocked requests (milliseconds) 'default_delay' => 0, // Security: only allow mocking for these hostnames (empty => all hosts allowed) 'allowed_hosts' => [], // Allowed application environments for Mocka activation (default: local only) // Extend this to enable in other envs, e.g. ['local', 'staging'] 'environments' => ['local'], // URL mappings 'mappings' => [ // Your API mappings here ], ];
- allowed_hosts: restricts Mocka activation to specific upstream hosts; leave empty to allow all.
- environments: restricts activation to these Laravel environments (default ['local']).
How It Works
- Activation Check: If enabled and allowed by environment/host, Mocka checks activation triggers in order: user allowlist,
withOptions(['mocka' => true]), orX-Mockaheader - URL Matching: If the user should be mocked, it matches the request URL against the configured mappings
- Mock Loading: Loads the appropriate mock file and extracts the response using dot notation
- Template Processing: Processes any template variables (faker, time functions, etc.)
- Response Simulation: Returns the mock response with optional delays or errors
- Logging: Logs whether the request was mocked or passed through
Testing
composer test
Security
If you discover any security related issues, please email metalogico@gmail.com instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information.
Made with ☕ in Italy
metalogico/laravel-mocka 适用场景与选型建议
metalogico/laravel-mocka 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 35 次下载、GitHub Stars 达 18, 最近一次更新时间为 2025 年 08 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「testing」 「laravel」 「mocks」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 metalogico/laravel-mocka 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 metalogico/laravel-mocka 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 metalogico/laravel-mocka 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Testing Suite For Lumen like Laravel does.
A PSR-7 compatible library for making CRUD API endpoints
The PHP SDK for Checkmango
Alfabank REST API integration
The testing extension of TYPO3voilà.
Auto-generate dummy data with realistic relationships per Model-like config classes
统计信息
- 总下载量: 35
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 18
- 点击次数: 28
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-20