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

Fetchapi Laravel Package

yyy/fetchapi

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yyy/fetchapi
    
  2. Publish Configuration

    php artisan vendor:publish --provider="YYY\FetchApi\Pay\ServiceProvider"
    
    • Locate the published config at config/fetchapi.php and update API endpoints, credentials, or default settings.
  3. First Use Case: Making an API Request

    use YYY\FetchApi\Pay\Api;
    
    $api = new Api(config('fetchapi.default_endpoint'));
    $response = $api->get('/endpoint', ['param' => 'value']);
    
  4. Stubbing for Testing

    use YYY\FetchApi\Pay\Stub;
    
    $stub = new Stub();
    $response = $stub->mockResponse('/endpoint', ['status' => 200, 'data' => []]);
    

Implementation Patterns

Core Workflows

  1. Request Handling

    • Use Api class for HTTP requests with built-in methods (get, post, put, delete).
    • Pass request data via RequestData class for structured payloads:
      $requestData = new RequestData(['key' => 'value']);
      $response = $api->post('/endpoint', $requestData);
      
  2. Interface-Driven Development

    • Implement interfaces (InterfacePay, InterfaceApi) for type safety and dependency injection:
      class MyPayService implements InterfacePay {
          public function processPayment(RequestData $data) {
              $api = new Api(config('fetchapi.endpoints.payment'));
              return $api->post('/pay', $data);
          }
      }
      
  3. Event Handling

    • Use InterfaceEvent to listen to API lifecycle events (e.g., onBeforeRequest, onAfterResponse):
      class MyEventListener implements InterfaceEvent {
          public function onBeforeRequest($request) {
              // Modify request (e.g., add auth headers)
          }
      }
      
  4. Stubbing for Tests

    • Replace Api with Stub in tests to mock responses:
      $this->app->bind(Api::class, function () {
          return new Stub();
      });
      

Integration Tips

  • Middleware: Wrap Api calls in middleware for logging, retries, or auth.
  • Service Container: Bind interfaces to implementations in AppServiceProvider:
    $this->app->bind(InterfaceApi::class, function () {
        return new Api(config('fetchapi.endpoints.default'));
    });
    
  • Configuration: Use config('fetchapi') for dynamic endpoint switching.

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • Published config may not auto-load. Ensure config/fetchapi.php is included in config/app.php under files.
    • Default values in Api constructor may conflict with published config. Explicitly pass endpoints:
      $api = new Api(config('fetchapi.endpoints.custom'));
      
  2. Stubbing Quirks

    • Stub does not auto-register. Manually bind it in tests or use a trait:
      trait UsesFetchApiStub {
          protected function stubApi() {
              $this->app->bind(Api::class, Stub::class);
          }
      }
      
  3. Interface Inconsistencies

    • InterfaceErr is undocumented. Assume it handles errors; implement custom error parsing if needed:
      try {
          $response = $api->get('/endpoint');
      } catch (Exception $e) {
          $errorHandler = new MyErrorHandler();
          $errorHandler->handle($e);
      }
      
  4. RequestData Validation

    • RequestData lacks built-in validation. Use Laravel’s Validator or a library like respect/validation:
      use Respect\Validation\Validator as v;
      
      if (!v::keySet(['required_field'])->validate($requestData->toArray())) {
          throw new \InvalidArgumentException('Missing required field');
      }
      

Debugging Tips

  • Logging Responses Add a listener to InterfaceEvent:

    public function onAfterResponse($response) {
        \Log::debug('API Response:', ['data' => $response->getData()]);
    }
    
  • Retry Logic Implement exponential backoff in middleware:

    $api->withRetry(3, function ($attempt) {
        return $attempt <= 3;
    });
    
  • Endpoint Switching Use config caching to avoid runtime lookups:

    $endpoint = config('fetchapi.endpoints.' . config('app.env'));
    

Extension Points

  1. Custom Request Methods Extend Api to add methods like patch or head:

    class ExtendedApi extends Api {
        public function patch($endpoint, $data = []) {
            return $this->request('PATCH', $endpoint, $data);
        }
    }
    
  2. Response Decorators Create a decorator for Api to transform responses:

    class ResponseDecorator {
        public function __construct(private Api $api) {}
    
        public function get($endpoint) {
            $response = $this->api->get($endpoint);
            return $this->transform($response);
        }
    
        private function transform($response) {
            // Custom logic (e.g., flatten arrays)
            return $response->getData();
        }
    }
    
  3. Event-Driven Extensions Dispatch Laravel events in InterfaceEvent implementations:

    public function onAfterResponse($response) {
        event(new ApiResponseEvent($response));
    }
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat