Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Restclientbundle Laravel Package

ci/restclientbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require circleofnice/restclientbundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        CircleOfNice\RestClientBundle\CircleOfNiceRestClientBundle::class => ['all' => true],
    ];
    
  2. First Use Case Inject the RestClient service into your controller or service:

    use CircleOfNice\RestClientBundle\RestClient;
    
    public function __construct(RestClient $restClient) {
        $this->restClient = $restClient;
    }
    

    Make a simple GET request:

    $response = $this->restClient->get('https://api.example.com/users');
    $data = json_decode($response->getContent(), true);
    
  3. Where to Look First

    • Service Configuration: Check config/packages/circle_of_nice_rest_client.yaml for default settings (e.g., timeout, headers).
    • Documentation: The README and src/RestClient.php for method signatures and response handling.
    • Symfony Response: Leverage Symfony’s Response object methods (e.g., getStatusCode(), getHeaders()).

Implementation Patterns

Core Workflows

  1. Basic CRUD Operations Use the intuitive HTTP method wrappers:

    // Create
    $response = $this->restClient->post('https://api.example.com/users', [
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]);
    
    // Read
    $response = $this->restClient->get('https://api.example.com/users/1');
    
    // Update
    $response = $this->restClient->put('https://api.example.com/users/1', [
        'name' => 'Updated Name'
    ]);
    
    // Delete
    $response = $this->restClient->delete('https://api.example.com/users/1');
    
  2. Handling Responses Treat responses as Symfony Response objects:

    if ($response->isSuccessful()) {
        $data = json_decode($response->getContent(), true);
    } else {
        throw new \RuntimeException('API Error: ' . $response->getStatusCode());
    }
    
  3. Authentication Add headers globally (e.g., in config) or per-request:

    # config/packages/circle_of_nice_rest_client.yaml
    circle_of_nice_rest_client:
        default_options:
            headers:
                Authorization: "Bearer YOUR_TOKEN"
    

    Or dynamically:

    $this->restClient->get('https://api.example.com/protected', [], [
        'headers' => ['X-API-KEY' => 'secret_key']
    ]);
    
  4. Error Handling Use Symfony’s HttpException or custom exceptions:

    try {
        $response = $this->restClient->get('https://api.example.com/fail');
    } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
        // Handle HTTP errors (4xx, 5xx)
    }
    
  5. Integration with Symfony Components

    • Serializer: Deserialize responses directly:
      $data = $this->serializer->deserialize($response->getContent(), 'array', 'json');
      
    • Messenger: Dispatch API calls as messages for async processing.

Advanced Patterns

  1. Custom Middleware Extend the RestClient to add preprocessing/postprocessing:

    use CircleOfNice\RestClientBundle\RestClientInterface;
    
    class CustomRestClient implements RestClientInterface {
        private $decorated;
    
        public function __construct(RestClient $decorated) {
            $this->decorated = $decorated;
        }
    
        public function get($url, array $options = []) {
            // Pre-process (e.g., add logging)
            $response = $this->decorated->get($url, $options);
            // Post-process (e.g., transform data)
            return $response;
        }
    }
    

    Register as a service:

    services:
        App\Service\CustomRestClient:
            decorates: circle_of_nice_rest_client.rest_client
            arguments: ['@App\Service\CustomRestClient.inner']
    
  2. Rate Limiting Use Symfony’s Stopwatch to track and throttle requests:

    $stopwatch = $this->container->get('debug.stopwatch');
    if ($stopwatch->section('api_rate_limit')->getDuration() < 1000) {
        $this->restClient->get('https://api.example.com/rate-limited');
    }
    
  3. Caching Responses Cache responses with Symfony’s HttpCache or Cache component:

    $cache = $this->container->get('cache.app');
    $cacheKey = 'api_users_' . md5($url);
    if (!$cache->has($cacheKey)) {
        $response = $this->restClient->get($url);
        $cache->set($cacheKey, $response->getContent(), 3600);
    } else {
        $response = new Response($cache->get($cacheKey));
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2019; verify compatibility with modern PHP/Symfony (e.g., 8.x).
    • Consider forking or replacing with symfony/http-client if critical bugs arise.
  2. Leaky Abstraction

    • Underlying curl options may still leak (e.g., CURLOPT_* constants). Avoid relying on undocumented behavior.
    • Example: Custom headers might require raw curl options:
      $this->restClient->get($url, [], [
          'curl_options' => [CURLOPT_HTTPHEADER => ['X-Raw-Header: value']]
      ]);
      
  3. Response Handling

    • Non-JSON APIs (e.g., XML) require manual parsing:
      $xml = simplexml_load_string($response->getContent());
      
    • Always check isSuccessful() or status codes before parsing.
  4. Configuration Overrides

    • Global config (default_options) may override per-request settings unintentionally. Test edge cases:
      # config/packages/circle_of_nice_rest_client.yaml
      circle_of_nice_rest_client:
          default_options:
              timeout: 30  # Overrides all requests unless specified otherwise
      
  5. SSL/TLS Issues

    • curl may fail silently on self-signed certs. Explicitly allow insecure options:
      $this->restClient->get($url, [], [
          'curl_options' => [CURLOPT_SSL_VERIFYPEER => false] // Use cautiously!
      ]);
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        rest_client:
            type: stream
            path: "%kernel.logs_dir%/rest_client.log"
            level: debug
            channels: ["!event"]
    

    Then enable debug mode in RestClient:

    $this->restClient->setDebug(true);
    
  2. Inspect Raw cURL Command Use CURLOPT_VERBOSE to log the exact cURL command:

    $this->restClient->get($url, [], [
        'curl_options' => [
            CURLOPT_VERBOSE => true,
            CURLOPT_STDERR => fopen('php://temp', 'w+')
        ]
    ]);
    
  3. Symfony Profiler Use the Web Profiler to inspect Response objects and headers:

    $response = $this->restClient->get('https://api.example.com/debug');
    $this->addFlash('debug', $response->getStatusCode());
    

Extension Points

  1. Custom Response Transformers Decorate the RestClient to transform responses:

    class TransformerRestClient implements RestClientInterface {
        public function get($url, array $options = []) {
            $response = $this->decorated->get($url, $options);
            $content = $response->getContent();
            $data = json_decode($content, true);
            // Custom logic (e.g., flatten arrays)
            $response->setContent(json_encode($data));
            return $response;
        }
    }
    
  2. Plugin System Create a RestClientPlugin interface to extend functionality:

    interface RestClientPluginInterface {
        public function onBeforeRequest(RestClient $client, string $method, string $url, array $options);
        public function onAfterResponse(RestClient $client, Response $response, string $method, string $url);
    }
    

    Register plugins in the RestClient constructor.

  3. **Event

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor