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

Adback Sdk Php Laravel Package

adback/adback-sdk-php

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require adback/adback-sdk-php
  1. Configure a cache driver (Redis or MySQL recommended):

    // Example: Redis setup
    $redis = new \Redis();
    $redis->connect('127.0.0.1');
    $cache = new \Adback\ApiClient\Driver\RedisScriptCache($redis);
    
  2. First use case: Fetch and cache AdBack scripts

    $client = new \Adback\ApiClient\Client\Client();
    $query = new \Adback\ApiClient\Query\ScriptUrlQuery($client, $cache, 'your-adback-token');
    $query->execute(); // Populates cache
    
  3. Render the script in Blade (Laravel):

    // In a Blade template (e.g., `layouts.app`)
    echo app(\Adback\ApiClient\Generator\AnalyticsScriptGenerator::class, ['cache' => $cache])->generate();
    

Implementation Patterns

1. Cache Initialization Workflow

  • Cron Job for Cache Warmup: Schedule a Laravel command (artisan schedule) to run ScriptUrlQuery or FullScriptQuery periodically (e.g., daily) to ensure fresh data:

    // app/Console/Commands/WarmAdbackCache.php
    class WarmAdbackCache extends Command {
        protected $signature = 'adback:warm-cache';
        public function handle() {
            $cache = resolve(RedisScriptCache::class);
            $query = new ScriptUrlQuery(new Client(), $cache, config('adback.token'));
            $query->execute();
            $this->info('AdBack cache warmed!');
        }
    }
    
  • Service Provider Binding: Bind the cache driver and generators in AppServiceProvider for dependency injection:

    public function register() {
        $this->app->singleton(RedisScriptCache::class, function () {
            $redis = new \Redis();
            $redis->connect(config('cache.redis.host'));
            return new RedisScriptCache($redis);
        });
    }
    

2. Dynamic Script Rendering

  • Middleware for Head Injection: Use middleware to inject the AdBack script into the <head> of all pages:

    // app/Http/Middleware/InjectAdbackScript.php
    public function handle($request, Closure $next) {
        $response = $next($request);
        $generator = app(AnalyticsScriptGenerator::class);
        $response->getContent()
            ->insert(strpos($response->getContent(), '</head>'),
            $generator->generate());
        return $response;
    }
    
  • Conditional Rendering: Skip AdBack scripts for non-HTML responses or specific routes:

    if ($request->wantsJson() || $request->is('admin/*')) {
        return $next($request);
    }
    

3. Environment-Specific Config

  • Config File: Define AdBack settings in config/adback.php:

    return [
        'token' => env('ADBACK_TOKEN'),
        'cache_driver' => env('ADBACK_CACHE', 'redis'),
        'ttl' => 86400, // Cache TTL in seconds
    ];
    
  • Cache Driver Switching: Dynamically select the cache driver based on config:

    $cache = config('adback.cache_driver') === 'redis'
        ? resolve(RedisScriptCache::class)
        : resolve(PdoScriptCache::class);
    

4. Testing Patterns

  • Mock the Cache Layer: Use Laravel’s mocking to test script generation without hitting AdBack’s API:
    $mockCache = Mockery::mock(ScriptCacheInterface::class);
    $mockCache->shouldReceive('get')
        ->with('script_url')
        ->andReturn('<script>AdBackMockScript</script>');
    
    $generator = new AnalyticsScriptGenerator($mockCache);
    $this->assertStringContainsString('AdBackMockScript', $generator->generate());
    

Gotchas and Tips

1. Cache Invalidation Pitfalls

  • TTL Management: The package doesn’t auto-expire cached scripts. Manually set TTL when storing data in Redis/MySQL:

    $redis->setex('script_url', config('adback.ttl'), $script);
    

    Tip: Use Laravel’s cache facade for consistency:

    Cache::put('adback_script', $script, config('adback.ttl'));
    
  • Manual Cache Clearing: If AdBack’s API changes unexpectedly, clear the cache manually:

    $redis->del('script_url');
    // Or for MySQL:
    DB::table('adback_cache_table')->where('our_key', 'script_url')->delete();
    

2. API Rate Limiting

  • Error Handling: The Client class may throw exceptions on API failures. Wrap queries in try-catch:
    try {
        $query->execute();
    } catch (\Exception $e) {
        Log::error("AdBack API failed: " . $e->getMessage());
        // Fallback to stale cache or silent fail
    }
    
    Tip: Implement a retry mechanism for transient failures.

3. Performance Considerations

  • Avoid Blocking Requests: Fetching scripts on every page load can slow down responses. Pre-fetch during low-traffic periods (e.g., nightly cron job).

  • Redis vs. MySQL: Redis is faster but requires persistence setup. MySQL is more stable but slower. Benchmark for your use case.

4. Extension Points

  • Custom Script Generators: Extend AnalyticsScriptGenerator to modify script output:

    class CustomScriptGenerator extends AnalyticsScriptGenerator {
        public function generate() {
            $script = parent::generate();
            return str_replace('data-adback', 'data-custom-adback', $script);
        }
    }
    
  • Multi-Token Support: The package assumes a single token. For multi-account setups, create a wrapper class:

    class AdbackManager {
        private $clients = [];
    
        public function getClient(string $token) {
            return $this->clients[$token] ?? $this->clients[$token] = new Client($token);
        }
    }
    

5. Debugging Tips

  • Log Raw Responses: Enable debug logging for the Client to inspect API responses:

    $client = new Client();
    $client->setLogger(new \Monolog\Logger('adback', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/adback.log'))
    ]));
    
  • Validate Cache Keys: Ensure cache keys match those used in ScriptUrlQuery/FullScriptQuery (e.g., script_url, full_script). Typos here will cause silent failures.

6. Deprecation Notes

  • Outdated Package: Last updated in 2018. Test thoroughly in staging, especially:

    • API endpoint compatibility (AdBack may have changed).
    • PHP version support (may need composer require ext-redis or ext-pdo_mysql).
  • Alternatives: If the package is too limiting, consider:

    • Direct API calls with Guzzle.
    • Laravel’s HTTP client for caching responses.

```markdown
### 7. Laravel-Specific Integrations
- **Service Provider Binding**:
  Bind the AdBack client and generators as singletons in `AppServiceProvider`:
  ```php
  public function register() {
      $this->app->singleton(Client::class, function () {
          $client = new Client();
          $client->setToken(config('adback.token'));
          return $client;
      });

      $this->app->bind(AnalyticsScriptGenerator::class, function ($app) {
          $cache = $app->make(config('adback.cache_driver') === 'redis'
              ? RedisScriptCache::class
              : PdoScriptCache::class);
          return new AnalyticsScriptGenerator($cache);
      });
  }
  • View Composers: Use a composer to inject scripts into all views:

    View::composer('*', function ($view) {
        if (!$view->getName() === 'layouts.app') {
            $view->with('adbackScript', app(AnalyticsScriptGenerator::class)->generate());
        }
    });
    
  • Environment Variables: Store the AdBack token in .env:

    ADBACK_TOKEN=your_token_here
    ADBACK_CACHE=redis
    

8. Common Anti-Patterns

  • Hardcoding Tokens: Never hardcode your-token in code. Always use environment variables or Laravel’s config.

  • Ignoring Cache Expiry: Relying on AdBack’s API without checking cache expiry can lead to stale data. Always validate TTL.

  • Overusing FullScriptQuery: FullScriptQuery fetches the entire script, which may be larger than needed

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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle