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

Embed Helpers Laravel Package

21torr/embed-helpers

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require 21torr/embed-helpers
    

    Register the bundle in config/bundles.php (Symfony):

    return [
        // ...
        EmbedHelpers\EmbedHelpersBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Embedding a YouTube Video Use the EmbedHelper service to generate an embed URL:

    use EmbedHelpers\EmbedHelper;
    
    class VideoController extends Controller
    {
        public function show(EmbedHelper $embedHelper)
        {
            $embedUrl = $embedHelper->getEmbedUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
            return view('video.show', compact('embedUrl'));
        }
    }
    
  3. Key Configuration Check config/packages/embed_helpers.yaml for default settings (e.g., platform-specific embed parameters). Override as needed:

    embed_helpers:
        platforms:
            youtube:
                embed_params:
                    rel: 0
                    autoplay: 1
    

Implementation Patterns

Common Workflows

  1. Dynamic Embed Generation Use the EmbedHelper to generate embeds dynamically in controllers or services:

    $embedHelper->getEmbedUrl('https://vimeo.com/123456', [
        'title' => false,
        'byline' => false,
    ]);
    
  2. Platform-Specific Customization Extend or override platform configurations via YAML or PHP:

    # config/packages/embed_helpers.yaml
    embed_helpers:
        platforms:
            vimeo:
                embed_params:
                    title: 0
                embed_template: '{{ url }}?title=0&byline=0&portrait=0'
    
  3. Embed Validation Validate URLs before embedding to avoid malformed requests:

    if ($embedHelper->isValidEmbedUrl('https://invalid.url')) {
        // Proceed
    }
    
  4. Twig Integration Pass the EmbedHelper to Twig templates for frontend rendering:

    {{ embedHelper.getEmbedUrl(videoUrl, {'autoplay': 1}) }}
    
  5. Batch Processing Process multiple embeds in a loop (e.g., for a gallery):

    $videos = Video::all();
    $embeds = $videos->map(fn ($video) => $embedHelper->getEmbedUrl($video->url));
    

Integration Tips

  1. Caching Embed URLs Cache generated embed URLs to reduce API calls (if the package supports it):

    $cacheKey = 'embed:'.$url;
    $embedUrl = Cache::remember($cacheKey, now()->addHours(1), function() use ($embedHelper, $url) {
        return $embedHelper->getEmbedUrl($url);
    });
    
  2. API Rate Limiting If embedding from APIs (e.g., Vimeo Pro), implement rate-limiting middleware:

    // src/Kernel.php
    protected function buildEmbedMiddleware($middleware)
    {
        $middleware[] = \EmbedHelpers\Middleware\RateLimitEmbeds::class;
        return array_merge($middleware, $this->middleware);
    }
    
  3. Fallback Mechanisms Handle unsupported platforms gracefully:

    try {
        $embedUrl = $embedHelper->getEmbedUrl('https://unsupported.com');
    } catch (\EmbedHelpers\Exception\UnsupportedPlatformException $e) {
        $embedUrl = null; // Fallback to static placeholder
    }
    
  4. Testing Embeds Mock the EmbedHelper in PHPUnit tests:

    $mockEmbedHelper = $this->createMock(EmbedHelper::class);
    $mockEmbedHelper->method('getEmbedUrl')->willReturn('https://mock-embed.com');
    $this->app->instance(EmbedHelper::class, $mockEmbedHelper);
    

Gotchas and Tips

Pitfalls

  1. Platform-Specific Quirks

    • Some platforms (e.g., Twitch) require OAuth tokens for embeds. The package may not handle this out-of-the-box.
    • Fix: Extend the EmbedHelper or create a custom service for tokenized platforms.
  2. URL Normalization Issues The package may not normalize URLs (e.g., youtube.com vs. www.youtube.com). Validate input URLs:

    $normalizedUrl = filter_var($url, FILTER_SANITIZE_URL);
    
  3. Missing Documentation for Advanced Use The package lacks examples for custom platform integration. Refer to the docs for updates.

  4. CORS Restrictions Embeds may fail if the platform enforces CORS policies. Test in a production-like environment.


Debugging Tips

  1. Enable Verbose Logging Configure Monolog to log embed generation:

    # config/packages/monolog.yaml
    handlers:
        embed:
            type: stream
            path: "%kernel.logs_dir%/embed.log"
            level: debug
    
  2. Check Generated HTML Use browser dev tools to inspect embeds for missing parameters or scripts:

    <!-- Example: Debug YouTube embed -->
    <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ?rel=0&autoplay=1" ...></iframe>
    
  3. Validate Platform Support Test with known-working URLs (e.g., YouTube, Vimeo) before custom platforms.


Extension Points

  1. Custom Platform Support Extend the EmbedHelper to add new platforms:

    // src/Service/CustomEmbedHelper.php
    class CustomEmbedHelper extends EmbedHelper
    {
        protected function getPlatformConfig(string $url): array
        {
            $config = parent::getPlatformConfig($url);
            if (str_contains($url, 'customplatform.com')) {
                $config = [
                    'embed_template' => '{{ url }}?custom_param=1',
                    'embed_params' => [],
                ];
            }
            return $config;
        }
    }
    
  2. Override Embed Templates Replace the default Twig template for embeds:

    {# templates/embed/default.html.twig #}
    <div class="custom-embed">
        <iframe src="{{ url }}" frameborder="0" allowfullscreen></iframe>
    </div>
    
  3. Event Listeners Listen for embed generation events (if the package supports them):

    // src/EventListener/EmbedListener.php
    class EmbedListener
    {
        public function onEmbedGenerated(EmbedEvent $event)
        {
            if ($event->getPlatform() === 'youtube') {
                $event->addParam('modestbranding', 1);
            }
        }
    }
    
  4. API Wrapper Integration Integrate with platform APIs (e.g., YouTube Data API) for dynamic embeds:

    $client = new \Google_Client();
    $youtube = new \Google_Service_YouTube($client);
    $video = $youtube->videos->listVideos(['id' => 'dQw4w9WgXcQ']);
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle