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

Laravel Advertising Module Laravel Package

zxf5115/laravel-advertising-module

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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
    
  2. 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'));
    }
    
  3. Key Configuration Check config/advertising.php for default settings like:

    • Ad types (e.g., banner, sidebar, popup)
    • Default ad slots and their positions
    • Cache settings for ad retrieval

Implementation Patterns

Core Workflows

1. Ad Management

  • 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),
    ]);
    
    • Bulk Operations: Use 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.

2. Integration with Views

  • 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');
    

3. API Endpoints

  • RESTful Routes Use Laravel’s built-in routing to expose ad management:

    Route::apiResource('ads', \Zxf5115\AdvertisingModule\Http\Controllers\AdController::class);
    
    • Custom Filters: Extend the controller to add filters (e.g., ?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',
        ],
    ];
    

4. Performance Optimization

  • 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')).


Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If you’ve manually created ads or ad_slots tables, drop them before running the package migrations to avoid duplicate column errors.
    • Check for reserved column names (e.g., position might conflict with Laravel’s default ordering).
  2. Cache Invalidation

    • Ads won’t update immediately if caching is enabled. Call Advertising::clearCache() after bulk operations or use cache()->forget() manually:
      cache()->forget("ad_{$adType}_{$position}");
      
  3. Ad Position Collisions

    • Ensure position values in ad_slots are unique. Duplicate positions may cause ads to override each other unexpectedly.
  4. Time Zone Issues

    • The 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').
  5. Facade vs. Service Container

    • Avoid overusing the Advertising facade in loops or performance-critical paths. Inject the service container binding directly:
      $this->adService = app('advertising');
      

Debugging Tips

  1. Log Ad Queries Enable query logging in AppServiceProvider:

    DB::enableQueryLog();
    $ads = Advertising::getAds(); // Fetch ads
    dd(DB::getQueryLog()); // Inspect the last query
    
  2. Check Event Listeners If ads aren’t triggering events, verify the AdPublished event is fired in Advertising::create() or Advertising::update().

  3. 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');
    

Extension Points

  1. 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
            }
        });
    }
    
  2. 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']);
    
  3. 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);
        }
    }
    
  4. 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);
    });
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver