Installation
composer require canaltp/sam-core-bundle
Add the bundle to config/bundles.php:
return [
// ...
CanalTP\SamCoreBundle\CanalTPSamCoreBundle::class => ['all' => true],
];
Configuration Publish the default config:
php bin/console canal-tp:sam-core:install
Update config/packages/canal_tp_sam_core.yaml with your API credentials and environment settings.
First Use Case: API Client Initialization
Inject the SamCoreClient service in a controller or command:
use CanalTP\SamCoreBundle\Client\SamCoreClient;
class MyController extends AbstractController
{
public function __construct(private SamCoreClient $samCoreClient) {}
public function index(): Response
{
$response = $this->samCoreClient->get('/api/v1/resource');
// Process response
}
}
API Requests Use the fluent interface for requests:
$this->samCoreClient
->setEndpoint('/api/v1/orders')
->setMethod('POST')
->setData(['order' => $orderData])
->send();
Authentication Handle OAuth2 or API keys via config:
canal_tp_sam_core:
api:
auth:
type: 'oauth2' # or 'api_key'
credentials: '%env(SAM_CORE_API_KEY)%'
Response Handling Decouple response processing:
$response = $this->samCoreClient->get('/api/v1/users');
$users = $response->getData(); // Parsed JSON
$status = $response->getStatusCode();
Event Listeners
Subscribe to sam_core.response events for centralized logging/validation:
// src/EventListener/SamCoreListener.php
public function onSamCoreResponse(ResponseEvent $event) {
if ($event->getResponse()->getStatusCode() >= 400) {
// Handle errors
}
}
Batch Processing
Use the BatchProcessor for bulk operations:
$processor = $this->samCoreClient->getBatchProcessor();
$processor->addRequest('GET', '/api/v1/orders/1')
->addRequest('GET', '/api/v1/orders/2')
->process();
Rate Limiting
canal_tp_sam_core:
api:
rate_limit: 100 # requests/minute
Caching Quirks
$this->samCoreClient->disableCache();
Deprecated Methods
SamCoreClient::call() (deprecated). Use send() instead.Environment-Specific Config
SAM_CORE_API_KEY is in .env, not hardcoded.Enable Verbose Logging
canal_tp_sam_core:
debug: true
Logs will appear in var/log/dev.log.
Mocking the Client
For tests, use the MockSamCoreClient:
$mockClient = new MockSamCoreClient();
$mockClient->shouldReceive('get')->andReturn(new Response(200, [], '{}'));
Common HTTP Errors
SAM_CORE_API_KEY or OAuth2 token.rate_limit or implement exponential backoff.Custom Response Transformers
Override CanalTP\SamCoreBundle\Response\Transformer\JsonTransformer to handle non-JSON APIs.
Middleware Integration Add custom middleware via config:
canal_tp_sam_core:
middleware:
- App\Middleware\CustomSamCoreMiddleware
Event Subscribers Extend functionality via events:
sam_core.request (before request)sam_core.response (after response)sam_core.error (on failure)Custom Endpoints Dynamically add endpoints at runtime:
$this->samCoreClient->addEndpoint('custom', 'https://custom-api.example.com');
How can I help you explore Laravel packages today?