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

Curlbundle Laravel Package

anchovy/curlbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require anchovy/curl-bundle
    
  2. Enable the Bundle in config/bundles.php:
    return [
        // ...
        Iman\AnchovyCURLBundle\ImanAnchovyCURLBundle::class => ['all' => true],
    ];
    
  3. Configure (optional) in config/packages/anchovy_curl.yaml:
    anchovy_curl:
        timeout: 30
        connect_timeout: 10
        default_headers: { 'User-Agent': 'MyApp/1.0' }
    
  4. First Use Case: Inject the CurlService into a controller or service:
    use Iman\AnchovyCURLBundle\Service\CurlService;
    
    class MyController extends AbstractController
    {
        public function __construct(private CurlService $curlService) {}
    
        public function fetchData()
        {
            $response = $this->curlService->get('https://api.example.com/data');
            return $this->json($response);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Basic HTTP Requests:

    $response = $curlService->get('https://api.example.com/endpoint');
    $response = $curlService->post('https://api.example.com/endpoint', ['key' => 'value']);
    $response = $curlService->put('https://api.example.com/endpoint', ['data' => 'payload']);
    
  2. Custom Headers/Options:

    $curlService->setHeaders(['Authorization' => 'Bearer token']);
    $curlService->setOptions(['CURLOPT_FOLLOWLOCATION' => true]);
    
  3. Handling Responses:

    $response = $curlService->execute();
    $body = $response->getBody(); // Raw response
    $json = $response->getJson(); // Parsed JSON
    $status = $response->getStatusCode();
    
  4. Async Requests (if supported):

    $curlService->async()->get('https://api.example.com/endpoint');
    

Integration Tips

  • Dependency Injection: Prefer injecting CurlService over instantiating it directly.
  • Configuration Overrides: Extend default config via YAML or environment variables.
  • Response Validation: Use Symfony’s Validator to validate API responses post-cURL.
  • Retry Logic: Implement a decorator pattern for retries (e.g., exponential backoff).

Common Use Cases

  • API Clients: Build dedicated services wrapping CurlService for specific APIs.
  • Webhooks: Handle incoming requests with post() and validate payloads.
  • Scraping: Use get() with custom headers/user-agents for scraping.

Gotchas and Tips

Pitfalls

  1. Symfony 2.x Legacy:

    • The bundle is designed for Symfony 2.3+ (not compatible with Symfony 3+ or 4+). Use a modern alternative (e.g., guzzlehttp/guzzle) for newer projects.
    • Workaround: Fork and adapt if migrating to newer Symfony versions.
  2. Response Handling:

    • getBody() returns raw response; always check getStatusCode() before parsing.
    • JSON parsing fails silently if the response isn’t valid JSON. Validate first:
      if ($response->getStatusCode() === 200 && $response->isJson()) {
          $data = $response->getJson();
      }
      
  3. Timeouts:

    • Default timeouts may be too short for slow APIs. Override in config:
      anchovy_curl:
          timeout: 60
      
  4. SSL Issues:

    • Disable SSL verification only for testing (never in production):
      $curlService->setOptions(['CURLOPT_SSL_VERIFYPEER' => false]);
      
    • For production, ensure CA certificates are bundled or use CURLOPT_CAINFO.
  5. Memory Leaks:

    • Always call curl_close() implicitly via execute() or get(). Avoid manual curl_* calls.

Debugging Tips

  • Enable Verbose Output:
    $curlService->setOptions(['CURLOPT_VERBOSE' => true]);
    
  • Log Responses:
    $this->logger->debug('API Response', ['body' => $response->getBody()]);
    
  • Check Headers: Use CURLOPT_HEADER to inspect raw headers:
    $curlService->setOptions(['CURLOPT_HEADER' => true]);
    

Extension Points

  1. Custom Response Classes: Extend Iman\AnchovyCURLBundle\Response\Response to add domain-specific methods:

    class ApiResponse extends Response
    {
        public function getData(): array
        {
            return $this->getJson()['data'] ?? [];
        }
    }
    
  2. Middleware: Decorate CurlService to add pre/post-processing:

    class AuthMiddlewareCurlService extends CurlService
    {
        public function __construct(CurlService $decoratedService)
        {
            $this->decoratedService = $decoratedService;
        }
    
        public function get($url)
        {
            $this->decoratedService->setHeaders(['Authorization' => $this->getToken()]);
            return $this->decoratedService->get($url);
        }
    }
    
  3. Event Listeners: Dispatch events before/after requests (e.g., logging, metrics):

    $dispatcher->addListener('curl.request', function (CurlEvent $event) {
        $this->logger->info('Request to ' . $event->getUrl());
    });
    

Configuration Quirks

  • Default Headers: Merge custom headers with defaults:
    anchovy_curl:
        default_headers:
            'X-Custom-Header': 'value'
    
  • Environment Variables: Override config via .env:
    ANCHOVY_CURL_TIMEOUT=45
    
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.
terminal42/code-quality-tools
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