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

Avito Laravel Package

baks-dev/avito

Laravel/PHP 8.4+ модуль для интеграции с Avito API: подключение через Composer, готовая основа для работы с запросами/данными Avito и набор PHPUnit тестов (группа avito). MIT лицензия.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/avito
    

    Ensure your project uses PHP 8.4+ and Laravel 10.x (or Symfony 6+ if applicable).

  2. Configuration Publish the package config (if available) or manually set credentials in .env:

    AVITO_API_TOKEN=your_partner_token_here
    AVITO_API_URL=https://api.avito.ru
    AVITO_CATEGORY_ID=123  # Optional: Default category for listings
    
  3. Service Registration Bind the Avito client in AppServiceProvider:

    use BaksDev\Avito\AvitoClient;
    
    public function register()
    {
        $this->app->bind(AvitoClient::class, function ($app) {
            return new AvitoClient(
                $app['config']['avito.token'],
                $app['config']['avito.api_url']
            );
        });
    }
    
  4. First Use Case: Fetch Ads Inject the client into a controller or service:

    use BaksDev\Avito\AvitoClient;
    
    public function showAds(AvitoClient $avito)
    {
        $ads = $avito->searchAds([
            'categoryId' => $this->categoryId,
            'limit' => 20,
            'sort' => 'PRICE_ASC'
        ]);
        return response()->json($ads);
    }
    
  5. Where to Look First

    • Service Class: vendor/baks-dev/avito/src/AvitoClient.php (core methods).
    • Exceptions: vendor/baks-dev/avito/src/Exceptions/ (error handling).
    • Tests: vendor/baks-dev/avito/tests/ (usage patterns and edge cases).
    • README: Focus on the installation and basic examples sections.

Implementation Patterns

Core Workflows

  1. Dependency Injection

    • Recommended: Use Laravel’s container to inject AvitoClient into services/controllers.
    • Example:
      public function __construct(private AvitoClient $avito) {}
      
    • Avoid: Global static calls (e.g., AvitoClient::search()) to maintain testability.
  2. Configuration Management

    • Centralize Avito settings in config/avito.php:
      return [
          'token' => env('AVITO_API_TOKEN'),
          'api_url' => env('AVITO_API_URL', 'https://api.avito.ru'),
          'default_category' => env('AVITO_CATEGORY_ID'),
          'timeout' => 30, // seconds
      ];
      
    • Publish config if the package supports it:
      php artisan vendor:publish --provider="BaksDev\Avito\AvitoServiceProvider"
      
  3. Request/Response Handling

    • Standardize Requests: Use a DTO or array for parameters:
      $params = [
          'categoryId' => 123,
          'filter' => ['price' => ['from' => 1000]],
          'sort' => 'PRICE_DESC'
      ];
      $ads = $avito->searchAds($params);
      
    • Response Parsing: The package likely returns raw Avito API responses. Normalize them:
      $ads = collect($avito->searchAds($params))->map(function ($ad) {
          return [
              'id' => $ad['id'],
              'title' => $ad['title'],
              'price' => $ad['price']['value'],
              'url' => $ad['url']
          ];
      });
      
  4. Authentication Patterns

    • Partner Token: For most endpoints, use a static token (stored in .env).
    • OAuth2 (if supported): If the package includes OAuth, configure it in config/avito.php:
      'auth' => [
          'client_id' => env('AVITO_OAUTH_CLIENT_ID'),
          'client_secret' => env('AVITO_OAUTH_CLIENT_SECRET'),
          'redirect_uri' => env('AVITO_OAUTH_REDIRECT_URI'),
      ],
      
    • Token Refresh: Implement a job to refresh tokens before expiry (if applicable).
  5. Error Handling

    • Wrap Calls in Try-Catch:
      try {
          $ads = $avito->searchAds($params);
      } catch (\BaksDev\Avito\Exceptions\AvitoException $e) {
          Log::error("Avito API error: " . $e->getMessage());
          return response()->json(['error' => 'Failed to fetch ads'], 500);
      }
      
    • Custom Exceptions: Extend the package’s exceptions for domain-specific handling:
      class AvitoRateLimitException extends \Exception {}
      
  6. Caching Strategies

    • Cache frequent or slow requests:
      $ads = Cache::remember("avito_ads_{$categoryId}", now()->addHours(1), function () use ($avito, $categoryId) {
          return $avito->searchAds(['categoryId' => $categoryId]);
      });
      
    • TTL: Set short TTLs (e.g., 1 hour) for dynamic data like ads.
  7. Queueing for Bulk Operations

    • Offload long-running or rate-limited operations to queues:
      dispatch(new SyncAvitoListings($avito, $listingIds))->onQueue('avito');
      
    • Example Job:
      use BaksDev\Avito\AvitoClient;
      use Illuminate\Bus\Queueable;
      use Illuminate\Contracts\Queue\ShouldQueue;
      
      class SyncAvitoListings implements ShouldQueue
      {
          use Queueable;
      
          public function __construct(
              private AvitoClient $avito,
              private array $listingIds
          ) {}
      
          public function handle()
          {
              foreach ($this->listingIds as $id) {
                  $this->avito->getListing($id);
              }
          }
      }
      
  8. Integration with Laravel Features

    • API Resources: Format Avito responses for Laravel APIs:
      public function toArray($request)
      {
          return [
              'data' => $this->ads->map(function ($ad) {
                  return new AvitoAdResource($ad);
              }),
          ];
      }
      
    • Events: Trigger custom events for Avito actions:
      event(new AvitoListingSynced($listing));
      
    • Notifications: Notify users of Avito-related actions (e.g., listing updates).

Advanced Patterns

  1. Webhook Listeners

    • If Avito supports webhooks, create a listener in Laravel:
      public function handle(AvitoWebhookEvent $event)
      {
          $payload = $event->payload;
          // Process webhook (e.g., update local DB)
      }
      
    • Verification: Validate webhook signatures (if required by Avito).
  2. Rate Limit Handling

    • Implement exponential backoff for retries:
      use Symfony\Component\Retry\Retry;
      
      $retry = new Retry(3, 1000); // 3 retries, 1s delay
      $ads = $retry->retry(function () use ($avito, $params) {
          return $avito->searchAds($params);
      });
      
  3. Testing Patterns

    • Mock the Client: Use Laravel’s mocking in tests:
      $mock = Mockery::mock(AvitoClient::class);
      $mock->shouldReceive('searchAds')->once()->andReturn($mockAds);
      $this->app->instance(AvitoClient::class, $mock);
      
    • Test Groups: Run Avito-specific tests with:
      php artisan test --group=avito
      
  4. Localization

    • Handle Avito’s Russian-language responses:
      $adTitle = Str::of($ad['title'])->ascii()->title();
      
  5. Monitoring

    • Track Avito API metrics (e.g., response times, errors) with Laravel Telescope or Prometheus:
      Telescope::addData(['avito' => [
          'response_time' => $endTime - $startTime,
          'status' => $response->status(),
      ]]);
      

Gotchas and Tips

Pitfalls

  1. Authentication Issues

    • Gotcha: Hardcoded tokens or missing token refresh logic.
    • Fix: Always store tokens in .env and implement refresh logic if using OAuth.
    • Tip: Use Laravel’s encryption service to securely store tokens in the database if needed.
  2. Rate Limiting

    • Gotcha: Avito enforces strict rate limits (e.g., 600 requests/hour). Uncached bulk operations can trigger 429 Too Many Requests.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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