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

Advertisement Bundle Laravel Package

ekyna/advertisement-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer (though note the last release was in 2015—verify compatibility with your Laravel version):

    composer require ekyna/advertisement-bundle
    

    Register the bundle in config/app.php under extra.bundles (if using Symfony/Laravel bridge) or manually load it in AppServiceProvider:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        if (file_exists($path = __DIR__.'/../../vendor/ekyna/advertisement-bundle/AdvertisementBundle.php')) {
            $this->app->register(new \AdvertisementBundle\AdvertisementBundle());
        }
    }
    
  2. Database Migration Run the bundle’s migrations (if included) or manually create tables for:

    • advertisements (e.g., id, title, content, start_date, end_date, status)
    • advertisement_slots (e.g., id, name, priority, is_active)
  3. First Use Case Display a simple ad in a Blade template:

    // routes/web.php
    Route::get('/ads', [AdController::class, 'index']);
    
    // app/Http/Controllers/AdController.php
    public function index()
    {
        $ads = \AdvertisementBundle\Entity\Advertisement::active()->get();
        return view('ads.index', compact('ads'));
    }
    
    <!-- resources/views/ads/index.blade.php -->
    @foreach($ads as $ad)
        <div class="ad">
            <h3>{{ $ad->title }}</h3>
            <p>{{ $ad->content }}</p>
        </div>
    @endforeach
    

Implementation Patterns

Core Workflows

  1. Advertisement CRUD Use the bundle’s entity manager to create/update ads:

    $ad = new \AdvertisementBundle\Entity\Advertisement();
    $ad->setTitle('Summer Sale')
       ->setContent('20% off!')
       ->setStartDate(new \DateTime('2023-01-01'))
       ->setEndDate(new \DateTime('2023-12-31'))
       ->setStatus('published');
    $em->persist($ad);
    $em->flush();
    
  2. Slot-Based Rendering Assign ads to slots (e.g., "header", "sidebar") and fetch them contextually:

    $headerAds = \AdvertisementBundle\Entity\AdvertisementSlot::findBy(['name' => 'header'])
        ->first()
        ->getAdvertisements();
    
  3. Querying Active Ads Filter ads by date and status:

    $activeAds = \AdvertisementBundle\Entity\Advertisement::active()
        ->where('priority', '>', 1)
        ->orderBy('priority', 'DESC')
        ->limit(3)
        ->get();
    
  4. Caching Ads Cache ad queries to reduce DB load (Laravel’s cache helper):

    $ads = Cache::remember('active_ads', now()->addHours(1), function() {
        return \AdvertisementBundle\Entity\Advertisement::active()->get();
    });
    

Integration Tips

  • Laravel-Specific Adjustments: Replace Symfony’s EntityManager with Laravel’s Eloquent by extending the bundle’s entities or creating a facade:

    // app/Facades/Advertisement.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class Advertisement extends Facade {
        protected static function getFacadeAccessor() { return 'advertisement'; }
    }
    

    Register the facade in AppServiceProvider.

  • Custom Validation: Extend the Advertisement entity with Laravel’s validation rules:

    use Illuminate\Support\Facades\Validator;
    $validator = Validator::make($ad->toArray(), [
        'title' => 'required|max:255',
        'content' => 'required',
        'start_date' => 'required|date|before:end_date',
    ]);
    
  • API Endpoints: Use Laravel’s API resources to expose ads:

    // app/Http/Resources/AdResource.php
    public function toArray($request) {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'is_active' => $this->isActive(),
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Outdated Codebase

    • The bundle was last updated in 2015 and may not support:
      • Laravel 8/9 features (e.g., model binding, API resources).
      • PHP 8.x syntax (e.g., named arguments, match expressions).
    • Workaround: Fork the repo and update dependencies manually (e.g., replace Symfony components with Laravel equivalents).
  2. Missing Documentation

    • The README lacks installation/configuration steps. Key missing pieces:
      • Database schema (assume standard advertisements/slots tables).
      • Service configuration (e.g., advertisement.yml for Symfony).
    • Tip: Check the Symfony Bundle docs for bundle structure clues.
  3. Hardcoded Logic

    • The bundle may assume Symfony’s EntityManager or Doctrine ORM. Replace with Laravel’s Model:
      // Convert Doctrine entity to Eloquent model
      class Advertisement extends \Illuminate\Database\Eloquent\Model {
          protected $table = 'advertisements';
          // Add accessors for bundle-specific methods (e.g., isActive())
      }
      
  4. No Event System

    • The bundle lacks Laravel’s event system (e.g., advertisement.created). Workaround: Use model observers or service providers to hook into CRUD operations:
      // app/Providers/AdvertisementServiceProvider.php
      public function boot() {
          \AdvertisementBundle\Entity\Advertisement::created(function ($ad) {
              event(new \AdvertisementCreated($ad));
          });
      }
      

Debugging Tips

  1. Check for Deprecated Methods

    • Wrap bundle calls in try-catch blocks to handle deprecated Symfony methods:
      try {
          $ad->setTitle('Test'); // May throw error in newer PHP
      } catch (\Error $e) {
          $ad->title = 'Test'; // Fallback to direct property access
      }
      
  2. Database Schema Mismatches

    • If migrations fail, manually create tables:
      CREATE TABLE advertisements (
          id INT AUTO_INCREMENT PRIMARY KEY,
          title VARCHAR(255),
          content TEXT,
          start_date DATETIME,
          end_date DATETIME,
          status ENUM('draft', 'published', 'archived'),
          created_at TIMESTAMP,
          updated_at TIMESTAMP
      );
      
  3. Slot-Ad Relationships

    • The bundle may use Doctrine’s ManyToMany relationships. Convert to Laravel’s belongsToMany:
      // Advertisement.php
      public function slots() {
          return $this->belongsToMany(AdvertisementSlot::class);
      }
      

Extension Points

  1. Custom Ad Types

    • Extend the Advertisement entity to support rich content (e.g., HTML, images):
      // app/Models/CustomAdvertisement.php
      class CustomAdvertisement extends \AdvertisementBundle\Entity\Advertisement {
          public function getRenderedContent() {
              return "<div class='custom-ad'>" . $this->content . "</div>";
          }
      }
      
  2. Geotargeting

    • Add a location field to ads and filter by IP/geolocation:
      $userLocation = $request->ip() ?? 'default';
      $localAds = \AdvertisementBundle\Entity\Advertisement::where('location', $userLocation)->get();
      
  3. Analytics Integration

    • Track ad impressions/clicks using Laravel’s events or a package like spatie/analytics:
      event(new \AdImpression($ad, $request->ip()));
      
  4. Admin Panel

    • Integrate with Laravel Nova or Filament for a UI:
      // Nova Resource for Advertisements
      Nova::resources([
          new \AdvertisementNovaResource(),
      ]);
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware