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

Fox Post Parcel Laravel Package

answear/fox-post-parcel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require answear/fox-post-parcel
    

    No additional configuration is required—just require the package in your Laravel project.

  2. First Use Case: Fetch a list of FoxPost parcel shops (stations) via the GetParcelShops command:

    use Answear\FoxPostParcel\Command\GetParcelShops;
    
    $getParcelShops = new GetParcelShops();
    $stations = $getParcelShops->getParcelShops(); // Returns array of stations
    
  3. Where to Look First:

    • Command Class: GetParcelShops in src/Command/ is the primary entry point.
    • Exceptions: Check src/Exception/ for ServiceUnavailable and MalformedResponse handling.
    • API Docs: The package fetches data from https://cdn.foxpost.hu/apms.json (see release 3.0.2).

Implementation Patterns

Core Workflow

  1. Fetching Stations: Use the GetParcelShops command in a Laravel service or controller:

    public function findNearestStation(Request $request)
    {
        $stations = app(GetParcelShops::class)->getParcelShops();
        // Filter/process stations (e.g., by distance, availability)
        return response()->json($filteredStations);
    }
    
  2. Integration with Laravel:

    • Service Provider: Register the command as a singleton if reused frequently:
      public function register()
      {
          $this->app->singleton(GetParcelShops::class);
      }
      
    • Jobs/Queues: Dispatch the command asynchronously for long-running tasks:
      GetParcelShops::dispatch()->onQueue('foxpost');
      
  3. Data Processing: The response is an array of stations with keys like id, name, address, etc. Normalize it with Laravel’s collect():

    $stations = collect($getParcelShops->getParcelShops())
        ->map(fn ($station) => [
            'id' => $station['id'],
            'formatted_address' => $station['address']['formatted'],
        ]);
    
  4. Caching: Cache the response for 1 hour (or as needed) to avoid repeated API calls:

    $stations = Cache::remember('foxpost_stations', 3600, function () {
        return app(GetParcelShops::class)->getParcelShops();
    });
    

Advanced Patterns

  1. Dependency Injection: Inject GetParcelShops into constructors for testability:

    public function __construct(private GetParcelShops $getParcelShops) {}
    
  2. Custom Responses: Extend the command to add business logic:

    class EnhancedGetParcelShops extends GetParcelShops
    {
        public function getFilteredStations(array $filters = [])
        {
            $stations = parent::getParcelShops();
            return collect($stations)->filter($filters);
        }
    }
    
  3. Testing: Mock the command in unit tests:

    $mockCommand = $this->createMock(GetParcelShops::class);
    $mockCommand->method('getParcelShops')->willReturn([...]);
    $this->app->instance(GetParcelShops::class, $mockCommand);
    

Gotchas and Tips

Pitfalls

  1. API Unavailability:

    • The package throws ServiceUnavailable for Guzzle exceptions (e.g., network issues).
    • Fix: Implement a retry mechanism with Laravel’s retry helper or a queue job:
      try {
          $stations = $getParcelShops->getParcelShops();
      } catch (ServiceUnavailable $e) {
          retry(3, function () use ($getParcelShops) {
              return $getParcelShops->getParcelShops();
          });
      }
      
  2. Malformed Responses:

    • MalformedResponse is thrown if the API returns invalid data.
    • Debugging: Log the raw response to identify schema issues:
      try {
          $stations = $getParcelShops->getParcelShops();
      } catch (MalformedResponse $e) {
          Log::error('FoxPost API response:', ['response' => $e->getResponse()]);
      }
      
  3. PHP/Symfony Version Mismatch:

    • The package requires PHP 8.2+ and Symfony 7.1+ (see release 3.0.0).
    • Fix: Update dependencies or use an older version (e.g., 2.x for Symfony 6).
  4. Empty Array Elements:

    • The package allows empty array elements (see release 3.0.3).
    • Tip: Sanitize data if strict validation is needed:
      $stations = array_filter($stations, fn ($station) => !empty($station['id']));
      

Tips

  1. Timeout Handling:

    • Guzzle’s default timeout is 10 seconds (added in release 2.0.1).
    • Customize: Override the Guzzle client in a service provider:
      $this->app->bind(GetParcelShops::class, function ($app) {
          $client = new Client(['timeout' => 30]);
          return new GetParcelShops($client);
      });
      
  2. Logging:

    • Add debug logs for API calls:
      $getParcelShops = new GetParcelShops();
      $getParcelShops->setLogger($this->app->make(LoggerInterface::class));
      
  3. Extension Points:

    • Custom Endpoints: Extend GetParcelShops to support other FoxPost APIs:
      class CustomFoxPostClient extends GetParcelShops
      {
          protected function getApiUrl(): string
          {
              return 'https://custom-api.foxpost.hu/data';
          }
      }
      
    • Response Transformers: Use Symfony’s Serializer to convert responses to DTOs:
      $serializer = $this->app->make(SerializerInterface::class);
      $stations = $serializer->deserialize($response, StationDto::class, 'json');
      
  4. Performance:

    • Batch Processing: For large datasets, stream responses or use pagination if the API supports it.
    • Lazy Loading: Load stations on-demand in Blade views:
      @foreach(app(GetParcelShops::class)->getParcelShops() as $station)
          {{ $station['name'] }}
      @endforeach
      
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