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

Sock Api Bundle Laravel Package

digipolisgent/sock-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer in a Laravel project (via Symfony bridge if needed):

    composer require digipolisgent/sock-api-bundle
    

    Register the bundle in config/app.php (Symfony) or adapt the bridge layer for Laravel.

  2. Configuration Locate the default config in config/sock_api.yaml (Symfony) or equivalent Laravel config file. Key settings:

    sock_api:
        base_uri: "https://api.example.com/sock"
        api_key: "your_api_key_here"
        timeout: 30
    

    Publish the config if needed:

    php artisan vendor:publish --tag=sock-api-config
    
  3. First Use Case: API Client Initialization Inject the client into a Laravel service or controller:

    use DigipolisGent\SockApiBundle\Client\SockApiClient;
    
    class MyService {
        protected $sockClient;
    
        public function __construct(SockApiClient $sockClient) {
            $this->sockClient = $sockClient;
        }
    }
    

    Call an endpoint (e.g., GET /users):

    $response = $this->sockClient->get('/users');
    $data = json_decode($response->getBody(), true);
    

Implementation Patterns

Common Workflows

  1. RESTful Endpoint Calls Use the client for standard HTTP methods:

    // GET
    $this->sockClient->get('/endpoint', ['param' => 'value']);
    
    // POST
    $this->sockClient->post('/endpoint', ['data' => 'payload']);
    
    // PUT/PATCH/DELETE
    $this->sockClient->put('/endpoint', ['data' => 'payload']);
    
  2. Authentication

    • API Key: Passed via config (default).
    • Custom Headers: Override headers per request:
      $this->sockClient->withHeaders(['Authorization' => 'Bearer token'])->get('/secure');
      
  3. Error Handling Wrap calls in a try-catch:

    try {
        $response = $this->sockClient->get('/endpoint');
    } catch (\DigipolisGent\SockApiBundle\Exception\SockApiException $e) {
        Log::error("SOCK API Error: " . $e->getMessage());
        throw new \RuntimeException("Failed to fetch data", 0, $e);
    }
    
  4. Laravel Integration

    • Service Providers: Bind the client in AppServiceProvider:
      $this->app->bind(SockApiClient::class, function ($app) {
          return new SockApiClient($app['config']['sock_api']);
      });
      
    • Facades: Create a facade for cleaner syntax (optional):
      // app/Facades/SockApi.php
      namespace App\Facades;
      use Illuminate\Support\Facades\Facade;
      class SockApi extends Facade { protected static function getFacadeAccessor() { return 'sock.api'; } }
      
      Register in AppServiceProvider:
      $this->app->singleton('sock.api', function ($app) {
          return new \App\Facades\SockApi($app->make(SockApiClient::class));
      });
      
  5. Batch Operations Use loops for bulk requests (e.g., fetching multiple records):

    $ids = [1, 2, 3];
    $results = [];
    foreach ($ids as $id) {
        $results[$id] = $this->sockClient->get("/users/{$id}");
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2018; verify compatibility with modern PHP/Symfony/Laravel.
    • Test thoroughly with your stack (e.g., Symfony 4+ or Laravel 8+ may need polyfills).
  2. No Laravel-Specific Docs

    • Assumes Symfony DI; manual binding required in Laravel.
    • No built-in Laravel events or service container integration.
  3. Error Handling Gaps

    • Custom exceptions (SockApiException) may lack details. Extend or log raw responses:
      catch (\RuntimeException $e) {
          $response = $e->getPrevious()->getResponse();
          Log::debug("Raw response: " . $response->getBody());
      }
      
  4. Configuration Overrides

    • Hardcoded defaults (e.g., base_uri) may conflict with Laravel’s dynamic config. Override via:
      $client = new SockApiClient([
          'base_uri' => config('services.sock_api.uri'),
          'api_key' => config('services.sock_api.key'),
      ]);
      

Debugging Tips

  1. Enable Guzzle Debugging Add to config:

    sock_api:
        debug: true
    

    Or manually:

    $client = new SockApiClient([...], new \GuzzleHttp\Client(['debug' => true]));
    
  2. Mocking for Tests Use Laravel’s HTTP client or mock the SockApiClient:

    $mock = Mockery::mock(SockApiClient::class);
    $mock->shouldReceive('get')->andReturn((object)['body' => '{"test":1}']);
    
  3. Timeouts Default timeout (30s) may be too short for slow APIs. Adjust:

    sock_api:
        timeout: 60
    

Extension Points

  1. Custom Middleware Add request/response middleware via Guzzle:

    $client = new SockApiClient([...], new \GuzzleHttp\Client([
        'middleware' => [new \App\Middleware\AddCustomHeader()]
    ]));
    
  2. Response Transformers Extend the client to auto-transform responses:

    class ExtendedSockApiClient extends SockApiClient {
        public function get($endpoint, array $params = []) {
            $response = parent::get($endpoint, $params);
            return json_decode($response->getBody(), true);
        }
    }
    
  3. Event Dispatching Trigger Laravel events on API calls (e.g., sock.api.request):

    event(new SockApiRequestEvent($request, $endpoint));
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware