## Getting Started
### Minimal Setup
1. **Install the package**:
```bash
composer require adback/adback-sdk-php
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);
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
Render the script in Blade (Laravel):
// In a Blade template (e.g., `layouts.app`)
echo app(\Adback\ApiClient\Generator\AnalyticsScriptGenerator::class, ['cache' => $cache])->generate();
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);
});
}
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);
}
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);
$mockCache = Mockery::mock(ScriptCacheInterface::class);
$mockCache->shouldReceive('get')
->with('script_url')
->andReturn('<script>AdBackMockScript</script>');
$generator = new AnalyticsScriptGenerator($mockCache);
$this->assertStringContainsString('AdBackMockScript', $generator->generate());
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();
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.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.
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);
}
}
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.
Outdated Package: Last updated in 2018. Test thoroughly in staging, especially:
composer require ext-redis or ext-pdo_mysql).Alternatives: If the package is too limiting, consider:
```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
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
How can I help you explore Laravel packages today?