sanjokdangol/apicall
最新稳定版本:v0.1.0
Composer 安装命令:
composer require sanjokdangol/apicall
包简介
Internal API Call Service for Laravel - Make authenticated API requests within your application kernel
README 文档
README
Internal API call service for Laravel applications. Make authenticated API requests within your application kernel without external HTTP overhead.
Features
- 🚀 In-Process Requests - No external HTTP calls
- 🔐 User Authentication - Authenticate as any user
- 🎯 Fluent API - Beautiful, chainable interface
- 🧪 Testing Ready - Like
TestCase::actingAs() - 📝 Clean Response - Multiple response formats
- 🐛 Debugging - Built-in debugging utilities
- ⚡ Queue-Ready - Perfect for jobs and commands
- 🔒 Token-Based - Support for API tokens and scopes
Installation
Step 1: Add Repository (For Development)
In your project's composer.json, add the path repository:
"repositories": [ { "type": "path", "url": "packages/sanjokdangol/apicall" } ]
Step 2: Require the Package
composer require --dev sanjokdangol/apicall
Note: This package is meant for development and testing environments. It's added to
require-dev.
Step 3: Auto-Discovery
Laravel will auto-discover the service provider. To verify:
php artisan package:discover --ansi
Step 4: (Optional) Publish Configuration
php artisan vendor:publish --provider="Sanjokdangol\ApiCall\Providers\ApiCallServiceProvider" --tag="apicall-config"
This creates config/apicall.php for custom configuration.
Quick Start
Basic Usage
use Sanjokdangol\ApiCall\Facades\ApiCall; use App\Models\User; $user = User::find(1); // Simple GET request $posts = ApiCall::actingAs($user) ->clean() ->get('/api/posts'); // POST with data $response = ApiCall::actingAs($user) ->post('/api/posts', [ 'title' => 'My Post', 'body' => 'Content here' ]); // With debugging $response = ApiCall::actingAs($user) ->dd() ->put('/api/users/1', ['name' => 'Updated']);
In Controllers
namespace App\Http\Controllers; use ApiCall; use Illuminate\Http\Request; class PostController extends Controller { public function store(Request $request) { $user = auth()->user(); $post = ApiCall::actingAs($user) ->post('/api/posts', $request->validated()); return response()->json($post, 201); } }
In Services
namespace App\Services; use Sanjokdangol\ApiCall\Facades\ApiCall; class NotificationService { public function sendNotification($user, $data) { return ApiCall::actingAs($user) ->post('/api/notifications', $data); } }
In Jobs/Commands
namespace App\Jobs; use ApiCall; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; class SyncUserDataJob implements ShouldQueue { use Queueable; protected $user; public function __construct($user) { $this->user = $user; } public function handle() { $data = ApiCall::actingAs($this->user) ->clean() ->get('/api/user-data'); // Process data... } }
In Tests
namespace Tests\Feature; use Tests\TestCase; use ApiCall; use App\Models\User; class PostApiTest extends TestCase { public function test_user_can_create_post() { $user = User::factory()->create(); $response = ApiCall::actingAs($user) ->post('/api/posts', [ 'title' => 'Test Post', 'body' => 'Test content' ]); $this->assertArrayHasKey('id', $response); $this->assertEquals('Test Post', $response['title']); } }
API Reference
Authentication Methods
actingAs(Authenticatable $user, array $scopes = [], string $tokenName = 'ApiCall')
Authenticate as a specific user for API requests.
ApiCall::actingAs($user)->get('/api/posts'); ApiCall::actingAs($user, ['read', 'write'])->post('/api/posts', $data);
asUser(Authenticatable $user, array $scopes = [], string $tokenName = 'ApiCall')
Alias for actingAs().
ApiCall::asUser($user)->get('/api/posts');
withToken(string $token)
Use a specific API token instead of generating one.
ApiCall::withToken($token)->get('/api/posts');
HTTP Methods
get(string $url, array $query = [])
Perform a GET request.
$posts = ApiCall::actingAs($user)->get('/api/posts'); $post = ApiCall::actingAs($user)->get('/api/posts/1'); $filtered = ApiCall::actingAs($user)->get('/api/posts', ['status' => 'published']);
post(string $url, array $data = [])
Perform a POST request.
$post = ApiCall::actingAs($user)->post('/api/posts', [ 'title' => 'New Post', 'body' => 'Content' ]);
put(string $url, array $data = [])
Perform a PUT request.
$updated = ApiCall::actingAs($user)->put('/api/posts/1', [ 'title' => 'Updated Title' ]);
patch(string $url, array $data = [])
Perform a PATCH request.
$updated = ApiCall::actingAs($user)->patch('/api/posts/1', [ 'status' => 'published' ]);
delete(string $url, array $data = [])
Perform a DELETE request.
$result = ApiCall::actingAs($user)->delete('/api/posts/1');
Response Methods
clean(bool $state = true)
Return only the response data, not the full Response object.
$data = ApiCall::actingAs($user)->clean()->get('/api/posts'); // Returns: array or object
response(bool $state = true)
Return the full Response object.
$response = ApiCall::actingAs($user)->response()->get('/api/posts'); // Returns: Illuminate\Http\Response // Access: $response->getStatusCode(), $response->getContent(), etc.
dd(bool $state = true)
Debug the request and response, then exit.
ApiCall::actingAs($user)->dd()->post('/api/posts', $data); // Dumps request/response details and stops execution
Configuration
Publishing the Config File
php artisan vendor:publish --provider="Sanjokdangol\ApiCall\Providers\ApiCallServiceProvider" --tag="apicall-config"
Configuration Options
// config/apicall.php return [ // Enable/disable API call logging 'log' => env('APICALL_LOG', false), // Log channel 'log_channel' => env('APICALL_LOG_CHANNEL', 'single'), // Token name for authentication 'token_name' => env('APICALL_TOKEN_NAME', 'ApiCall'), // Default scopes 'default_scopes' => [], ];
Use Cases
1. Internal Service Communication
// Without leaving the app, call your own API endpoints $userData = ApiCall::actingAs($user)->get('/api/users/profile');
2. Testing API Endpoints
// Test as if making HTTP requests, but in-process $response = ApiCall::actingAs($user)->post('/api/posts', $data);
3. Background Jobs
// Execute API calls in queued jobs with proper user context dispatch(new ProcessUserDataJob($user)); // Inside the job ApiCall::actingAs($this->user)->post('/api/data/process', $data);
4. Cross-Module Communication
// Call APIs from other packages/modules $result = ApiCall::actingAs($user)->get('/api/dashboard/stats');
5. Webhooks & Event Handlers
// Handle events by making API calls public function handle(UserCreated $event) { ApiCall::actingAs($event->user)->post('/api/onboarding/start'); }
Package Directory Structure
packages/sanjokdangol/apicall/
├── src/
│ ├── Facades/
│ │ └── ApiCall.php # Facade for easy access
│ ├── Providers/
│ │ └── ApiCallServiceProvider.php # Service provider
│ └── Services/
│ └── ApiCall.php # Core service class
├── config/
│ └── apicall.php # Configuration file
├── database/ # Database files (if needed)
├── resources/ # Resources (if needed)
├── tests/
│ └── Feature/
│ └── ApiCallTest.php # Package tests
├── composer.json # Package dependencies
├── LICENSE.md # MIT License
├── README.md # This file
└── .gitignore # Git ignore rules
Development
Project Configuration
| Aspect | Details |
|---|---|
| Package Name | sanjokdangol/apicall |
| Namespace | Sanjokdangol\ApiCall |
| Facade | ApiCall |
| Service Key | apicall |
| Minimum PHP | 7.3 / 8.0+ |
| Minimum Laravel | 8.12+ |
| Type | Development Package |
| License | MIT |
Running Tests
# From package directory cd packages/sanjokdangol/apicall # Run tests ../../../vendor/bin/phpunit # Or from project root php artisan test packages/sanjokdangol/apicall/tests
Publishing Documentation
php artisan vendor:publish --provider="Sanjokdangol\ApiCall\Providers\ApiCallServiceProvider" --tag="apicall-docs"
Troubleshooting
Package Not Auto-Discovered
php artisan package:discover --ansi composer dump-autoload php artisan cache:clear
Facade Not Found
Ensure the package is installed:
composer show sanjokdangol/apicall
Manually register in config/app.php if needed:
'providers' => [ // ... Sanjokdangol\ApiCall\Providers\ApiCallServiceProvider::class, ], 'aliases' => [ // ... 'ApiCall' => Sanjokdangol\ApiCall\Facades\ApiCall::class, ],
Class Not Found
Clear and regenerate autoloader:
composer dump-autoload php artisan tinker > use Sanjokdangol\ApiCall\Facades\ApiCall;
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This package is open-source software licensed under the MIT license.
Support
For issues, questions, or suggestions, please open an issue on the repository.
Made with ❤️ for Laravel developers
---
## Key Updates Made:
1. ✅ Changed package name from `sanjokDangol/apicall` to `sanjokdangol/apicall`
2. ✅ Updated namespace from `SanjokDangol\ApiCall` to `Sanjokdangol\ApiCall`
3. ✅ Added `require-dev` note explaining development-only package
4. ✅ Added repository configuration instructions
5. ✅ Added comprehensive API reference
6. ✅ Added real-world use cases
7. ✅ Added configuration section
8. ✅ Added troubleshooting guide
9. ✅ Added development tips
10. ✅ Better organization and formatting
11. ✅ More code examples
12. ✅ Added jobs/commands examples
统计信息
- 总下载量: 14
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 3
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-25