Installation:
composer require dbstudios/link-bundle
Add to config/bundles.php (Symfony):
return [
// ...
DbStudios\LinkBundle\DbStudiosLinkBundle::class => ['all' => true],
];
Configuration: Publish the default config:
php bin/console dbstudios:link:install
Edit config/packages/dbstudios_link.yaml to define your link types (e.g., default, internal, external).
First Use Case: Generate a link in a Twig template:
{{ link('default', { path: 'app_homepage' }) }}
Or in PHP:
$link = $this->get('link_generator')->generate('default', ['path' => 'app_homepage']);
Link Generation:
$link = $this->get('link_generator')->generate('internal', ['_route' => 'user_profile', 'id' => $user->id]);
$link = $this->get('link_generator')->generate('external', ['url' => 'https://example.com', 'query' => ['utm_source' => 'newsletter']]);
Twig Integration:
{% set link = link('default', { path: 'contact' }) %}
<a href="{{ link|url }}">{{ link|title }}</a>
{{ link|isAbsolute }} {# Checks if link is absolute #}
Service Integration:
LinkGenerator into controllers/services:
public function __construct(private LinkGenerator $linkGenerator) {}
public function show() {
$link = $this->linkGenerator->generate('internal', ['_route' => 'product_show', 'id' => 1]);
}
Route-Based Links:
$link = $this->linkGenerator->generate('default', ['_route' => 'app_home']);
Asset Links:
# config/packages/dbstudios_link.yaml
types:
asset:
base_url: '%kernel.project_dir%/public/build'
$assetLink = $this->linkGenerator->generate('asset', ['path' => 'styles/main.css']);
Configuration Overrides:
base_url per environment in dbstudios_link.yaml.Route Resolution:
_route parameter for route-based links:
$link = $this->linkGenerator->generate('internal', ['_route' => 'nonexistent_route']); // Throws exception
php bin/console debug:router
Caching:
php bin/console cache:clear
Twig Auto-escaping:
|raw filter if escaping breaks HTML attributes:
<a href="{{ link|url|raw }}">Link</a>
External Links:
$url = 'https://' . parse_url($externalUrl, PHP_URL_HOST);
if (!filter_var($url, FILTER_VALIDATE_DOMAIN)) {
throw new \InvalidArgumentException('Invalid external URL');
}
Log Generated Links:
dbstudios_link.yaml:
debug: true
var/log/dev.log.Validate Config:
validate command:
php bin/console dbstudios:link:validate
Custom Link Types:
# config/services.yaml
services:
App\Link\CustomLinkGenerator:
tags: ['dbstudios.link.type']
DbStudios\LinkBundle\Generator\LinkGeneratorInterface.Performance:
types:
dynamic:
cache: false
Testing:
LinkGenerator in PHPUnit:
$mockLink = $this->createMock(Link::class);
$mockLink->method('getUrl')->willReturn('https://example.com');
$this->linkGenerator->expects($this->once())->method('generate')->willReturn($mockLink);
How can I help you explore Laravel packages today?