Installation:
composer require canaltp/tyr-bundle:1.1.x
Add the bundle to AppKernel.php:
new CanalTP\TyrBundle\CanalTPTyrBundle(),
Configure:
Update app/config.yml with your Tyr API endpoint:
canal_tp_tyr:
url: %tyr_url%
end_point_id: 2 # Optional
Define the tyr_url parameter in parameters.yml:
parameters:
tyr_url: http://tyr.dev.canaltp.fr/v0/
First Use Case: Inject the service via dependency injection or fetch it from the container:
$tyrApi = $this->get('canal_tp_tyr.api');
$user = $tyrApi->getUserByEmail('user@example.com');
Leverage Symfony’s DI container for cleaner code:
// In a controller/service
public function __construct(CanalTP\TyrBundle\Service\TyrApi $tyrApi) {
$this->tyrApi = $tyrApi;
}
Set the endpoint ID dynamically (e.g., per request or user):
$tyrApi->setEndPointId($request->get('endpoint_id'));
Wrap API calls in try-catch blocks to handle exceptions gracefully:
try {
$user = $tyrApi->getUserByEmail('user@example.com');
} catch (\Exception $e) {
$this->addFlash('error', 'Failed to fetch user: ' . $e->getMessage());
}
Use events to pre-process or post-process API responses:
// In a listener
public function onKernelRequest(GetResponseEvent $event) {
$tyrApi = $this->container->get('canal_tp_tyr.api');
$tyrApi->setEndPointId($this->getEndpointIdFromContext());
}
end_point_id: If not set in config.yml, ensure it’s dynamically set via setEndPointId() or the API will fail.url parameter in config.yml must end with / (e.g., http://tyr.dev/v0/). Omitting it may cause 404 errors.HttpClient under the hood. Enable debug mode to inspect requests:
# config.yml
framework:
http_client:
debug: true
AbstractTyrService to log raw responses for debugging:
$tyrApi->getClient()->getEventDispatcher()->addListener(
'response',
function ($event) {
$this->logger->debug('Tyr API Response:', ['response' => $event->getResponse()->getContent()]);
}
);
// src/Service/CustomTyrApi.php
class CustomTyrApi extends \CanalTP\TyrBundle\Service\TyrApi {
public function getCustomData($id) {
return $this->get('http_client')->request('GET', $this->url . 'custom/' . $id);
}
}
Register it as a service in services.yml:
services:
canal_tp_tyr.api:
class: App\Service\CustomTyrApi
arguments: ['@http_client', '%tyr_url%', '%kernel.debug%']
$cache = $this->container->get('cache.app');
$key = 'tyr_user_' . md5('user@example.com');
if (!$cache->has($key)) {
$user = $tyrApi->getUserByEmail('user@example.com');
$cache->set($key, $user, 3600); // Cache for 1 hour
} else {
$user = $cache->get($key);
}
How can I help you explore Laravel packages today?