zxf5115/laravel-advertising-module
Installation
composer require zxf5115/laravel-advertising-module
Publish the package configuration and migrations:
php artisan vendor:publish --provider="Zxf5115\AdvertisingModule\AdvertisingServiceProvider" --tag=config
php artisan vendor:publish --provider="Zxf5115\AdvertisingModule\AdvertisingServiceProvider" --tag=migrations
php artisan migrate
First Use Case: Displaying an Ad
Inject the Advertising facade into a controller or service:
use Zxf5115\AdvertisingModule\Facades\Advertising;
public function showAd()
{
$ad = Advertising::getAdByType('banner'); // Fetch a banner ad
return view('ads.show', compact('ad'));
}
Key Configuration
Check config/advertising.php for default settings like:
banner, sidebar, popup)Create/Update Ads
Use the Advertising facade to manage ads programmatically:
$ad = Advertising::create([
'type' => 'banner',
'title' => 'Summer Sale',
'content' => '<img src="..." alt="Sale">',
'position' => 'header',
'start_at' => now()->addDays(7),
'end_at' => now()->addDays(30),
]);
Advertising::update() or Advertising::delete() with array IDs.Ad Scheduling
Leverage the start_at and end_at fields for time-based ad rotation. The package likely auto-filters active ads.
Blade Directives
Register a custom Blade directive in AppServiceProvider:
Blade::directive('ad', function ($type) {
return "<?php echo \\Zxf5115\\AdvertisingModule\\Facades\\Advertising::renderAd('{$type}'); ?>";
});
Usage in Blade:
@ad('banner')
Dynamic Ad Slots Pass slot names or IDs to fetch context-aware ads:
$sidebarAd = Advertising::getAdBySlot('homepage-sidebar');
RESTful Routes Use Laravel’s built-in routing to expose ad management:
Route::apiResource('ads', \Zxf5115\AdvertisingModule\Http\Controllers\AdController::class);
?type=banner&position=header).Webhook for Ad Events
Listen for ad-related events (e.g., ad.published) in EventServiceProvider:
protected $listen = [
'Zxf5115\AdvertisingModule\Events\AdPublished' => [
'App\Listeners\NotifyAdTeam',
],
];
Caching Ads
Configure cache drivers in config/advertising.php:
'cache' => [
'enabled' => true,
'ttl' => 3600, // 1 hour
],
Manually clear cache when ads are updated:
Advertising::clearCache();
Lazy Loading
Use Advertising::getAdByType() with eager loading for related models (e.g., with('campaign')).
Migration Conflicts
ads or ad_slots tables, drop them before running the package migrations to avoid duplicate column errors.position might conflict with Laravel’s default ordering).Cache Invalidation
Advertising::clearCache() after bulk operations or use cache()->forget() manually:
cache()->forget("ad_{$adType}_{$position}");
Ad Position Collisions
position values in ad_slots are unique. Duplicate positions may cause ads to override each other unexpectedly.Time Zone Issues
start_at/end_at fields use the server’s time zone. Set config/app.php to your target time zone (e.g., 'timezone' => 'Asia/Shanghai').Facade vs. Service Container
Advertising facade in loops or performance-critical paths. Inject the service container binding directly:
$this->adService = app('advertising');
Log Ad Queries
Enable query logging in AppServiceProvider:
DB::enableQueryLog();
$ads = Advertising::getAds(); // Fetch ads
dd(DB::getQueryLog()); // Inspect the last query
Check Event Listeners
If ads aren’t triggering events, verify the AdPublished event is fired in Advertising::create() or Advertising::update().
Validate Ad Content
Sanitize ad content (e.g., htmlspecialchars()) if rendering user-generated ads to prevent XSS:
echo htmlspecialchars($ad->content, ENT_QUOTES, 'UTF-8');
Custom Ad Types
Extend the Ad model or use model events to add custom logic:
// app/Providers/AdServiceProvider.php
public function boot()
{
\Zxf5115\AdvertisingModule\Models\Ad::created(function ($ad) {
if ($ad->type === 'promo') {
// Custom logic for promo ads
}
});
}
Ad Targeting Rules
Add middleware to filter ads based on user segments (e.g., user->isPremium):
public function handle($request, Closure $next)
{
$request->merge(['ad_target' => 'premium']);
return $next($request);
}
Then query ads with:
Advertising::getAds(['target' => 'premium']);
Third-Party Ad Networks
Create a decorator for the Advertising facade to integrate with external APIs:
class ExternalAdDecorator
{
public function getAdByType($type)
{
$externalAd = $this->fetchFromExternalApi($type);
return $externalAd ?: app('advertising')->getAdByType($type);
}
}
Testing
Use the Advertising facade in feature tests:
public function test_ad_display()
{
$ad = Advertising::factory()->create(['type' => 'banner']);
$response = $this->get('/');
$response->assertSee($ad->title);
}
Mock the facade in unit tests:
$this->mock(Zxf5115\AdvertisingModule\Facades\Advertising::class, function ($mock) {
$mock->shouldReceive('getAdByType')->andReturn($fakeAd);
});
How can I help you explore Laravel packages today?