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],
];
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'));
}
}
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
Dynamic Embed Generation
Use the EmbedHelper to generate embeds dynamically in controllers or services:
$embedHelper->getEmbedUrl('https://vimeo.com/123456', [
'title' => false,
'byline' => false,
]);
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'
Embed Validation Validate URLs before embedding to avoid malformed requests:
if ($embedHelper->isValidEmbedUrl('https://invalid.url')) {
// Proceed
}
Twig Integration
Pass the EmbedHelper to Twig templates for frontend rendering:
{{ embedHelper.getEmbedUrl(videoUrl, {'autoplay': 1}) }}
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));
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);
});
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);
}
Fallback Mechanisms Handle unsupported platforms gracefully:
try {
$embedUrl = $embedHelper->getEmbedUrl('https://unsupported.com');
} catch (\EmbedHelpers\Exception\UnsupportedPlatformException $e) {
$embedUrl = null; // Fallback to static placeholder
}
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);
Platform-Specific Quirks
EmbedHelper or create a custom service for tokenized platforms.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);
Missing Documentation for Advanced Use The package lacks examples for custom platform integration. Refer to the docs for updates.
CORS Restrictions Embeds may fail if the platform enforces CORS policies. Test in a production-like environment.
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
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>
Validate Platform Support Test with known-working URLs (e.g., YouTube, Vimeo) before custom platforms.
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;
}
}
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>
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);
}
}
}
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']);
How can I help you explore Laravel packages today?