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

Megamarket Laravel Package

baks-dev/megamarket

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require baks-dev/megamarket
    php artisan vendor:publish --provider="BaksDev\Megamarket\MegamarketServiceProvider"
    
    • Publishes config files to config/megamarket.php.
  2. Configure Environment Add to .env:

    MEGAMARKET_TOKEN=your_api_token_here
    MESSENGER_TRANSPORT_DSN=redis://localhost:6379/1
    
  3. Run Asset Installation

    php artisan baks:assets:install
    
    • Sets up required files (e.g., queue transports, config templates).
  4. First API Call (Example) Use the bundle’s client to fetch products:

    use BaksDev\Megamarket\Client;
    
    $client = app(Client::class);
    $products = $client->products()->all();
    
  5. Queue Setup (Critical for Async Operations) Configure Messenger transport in config/megamarket.php:

    'transports' => [
        'default' => [
            'dsn' => env('MESSENGER_TRANSPORT_DSN'),
            'queue_name' => 'megamarket_default',
        ],
    ],
    

    Then register the transport in a service provider:

    $this->app->make(\BaksDev\Megamarket\Messenger\MessengerFactory::class)
        ->addTransport('default');
    

First Use Case: Syncing Catalog

  1. Trigger a Sync Job
    use BaksDev\Megamarket\Jobs\SyncCatalog;
    
    SyncCatalog::dispatch()->onQueue('megamarket_default');
    
  2. Process Results Listen for events (e.g., megamarket.catalog.synced) in an event subscriber:
    public function handleCatalogSynced(CatalogSyncedEvent $event)
    {
        // Update your database or trigger downstream actions
    }
    

Implementation Patterns

Core Workflows

1. API Integration Pattern

  • Use the Client Facade The bundle provides a fluent client interface for all Megamarket endpoints:

    $client = app(\BaksDev\Megamarket\Client::class);
    
    // Products
    $products = $client->products()->filter(['category_id' => 123])->limit(10)->get();
    
    // Orders
    $orders = $client->orders()->recent()->withItems()->get();
    
  • Customize Requests Extend the base client to add custom endpoints or modify requests:

    use BaksDev\Megamarket\Client;
    use BaksDev\Megamarket\Http\Request;
    
    class CustomClient extends Client
    {
        public function customEndpoint()
        {
            return $this->request(new Request('GET', '/custom/endpoint'));
        }
    }
    

2. Queue-Based Processing

  • Dispatch Jobs Use the provided jobs for async operations:

    use BaksDev\Megamarket\Jobs\SyncOrders;
    
    SyncOrders::dispatch(['status' => 'pending'])->onQueue('megamarket_orders');
    
  • Handle Failures Configure retry logic in config/megamarket.php:

    'retry_strategy' => [
        'max_retries' => 3,
        'delay' => 1000, // ms
        'max_delay' => 0,
        'multiplier' => 2,
    ],
    
  • Listen for Events Subscribe to job events to react to async operations:

    public function handleOrderSynced(OrderSyncedEvent $event)
    {
        // Update inventory, send notifications, etc.
    }
    

3. Data Transformation

  • Map API Responses to Eloquent Models Use the bundle’s mappers to transform Megamarket data:

    use BaksDev\Megamarket\Mappers\ProductMapper;
    
    $mapper = new ProductMapper();
    $product = $mapper->map($apiResponse);
    
  • Custom Mappers Extend base mappers for your domain:

    use BaksDev\Megamarket\Mappers\AbstractMapper;
    
    class CustomProductMapper extends AbstractMapper
    {
        protected function mapAttributes(array $data): array
        {
            $attributes = parent::mapAttributes($data);
            $attributes['custom_field'] = $data['vendor_specific_field'] ?? null;
            return $attributes;
        }
    }
    

4. Token Management

  • Rotate Tokens Automatically The bundle handles token rotation via Messenger. Configure multiple tokens in config/megamarket.php:

    'tokens' => [
        'primary' => [
            'token' => env('MEGAMARKET_PRIMARY_TOKEN'),
            'transport' => 'default',
        ],
        'backup' => [
            'token' => env('MEGAMARKET_BACKUP_TOKEN'),
            'transport' => 'backup_queue',
        ],
    ],
    
  • Switch Tokens Dynamically Use the TokenManager to switch tokens at runtime:

    $tokenManager = app(\BaksDev\Megamarket\TokenManager::class);
    $tokenManager->setActiveToken('backup');
    

Integration Tips

Laravel-Symfony Bridge

  • Wrap Symfony Services Create Laravel facades for Symfony services to maintain consistency:

    // app/Facades/Megamarket.php
    public static function client()
    {
        return app(\BaksDev\Megamarket\Client::class);
    }
    
  • Use Laravel’s Container Bind Symfony services to Laravel’s container in a service provider:

    $this->app->bind(
        \BaksDev\Megamarket\Client::class,
        \BaksDev\Megamarket\Client::class
    );
    

Queue Integration

  • Laravel Queue Workers Run Laravel’s queue workers to process Messenger jobs:

    php artisan queue:work --queue=megamarket_default
    
  • Custom Transport Adapters Extend TransportInterface to use Laravel’s queue drivers:

    use Symfony\Component\Messenger\Transport\TransportInterface;
    use Illuminate\Queue\QueueManager;
    
    class LaravelTransport implements TransportInterface
    {
        public function __construct(private QueueManager $queue)
        {}
    
        public function send(Envelope $envelope): Envelope
        {
            $this->queue->push(new MessengerJob($envelope));
            return $envelope;
        }
    }
    

Event-Driven Architecture

  • Publish Custom Events Extend the bundle’s events for your use case:

    use BaksDev\Megamarket\Events\Event;
    
    class CustomEvent extends Event
    {
        public function __construct(public string $data)
        {}
    }
    
  • Listen Globally Register event listeners in EventServiceProvider:

    protected $listen = [
        \BaksDev\Megamarket\Events\OrderCreated::class => [
            \App\Listeners\ProcessOrder::class,
        ],
    ];
    

Gotchas and Tips

Pitfalls

1. Symfony-Laravel Incompatibilities

  • Issue: Symfony Messenger expects specific queue transports (e.g., symfony/messenger-transport-doctrine). Laravel’s queue system may not align perfectly.

  • Issue: Doctrine ORM vs. Eloquent. The bundle uses Doctrine, which may conflict with Laravel’s Eloquent.

    • Fix: Avoid direct ORM usage. Use repositories or translate queries to Eloquent:
      // Instead of:
      $entityManager->getRepository(Product::class)->findAll();
      
      // Use:
      Product::query()->where('api_id', $apiId)->first();
      

2. Token Management Quirks

  • Issue: Token rotation may fail silently if the backup token is invalid.

    • Fix: Add validation in TokenManager:
      public function setActiveToken(string $tokenName): void
      {
          if (!$this->isTokenValid($tokenName)) {
              throw new \RuntimeException("Token {$tokenName} is invalid.");
          }
          $this->activeToken = $tokenName;
      }
      
  • Issue: Multiple tokens may cause race conditions in async jobs.

    • Fix: Use a dedicated queue for each token to isolate operations.

3. Queue Retry Logic

  • Issue: Retry delays may not align with Megamarket’s rate limits.
    • Fix: Customize the retry strategy per endpoint:
      'retry_strategy' => [
          'products' => [
              'delay' => 200
      
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.
symfony/ai-symfony-mate-extension
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata