22

I'm going to use Symfony2 to sent periodically a newsletter to many users. I've to include a permalink to the HTML email for those who experience problems in reading them with an email client.

Anyway, assuming that i'm sending the newsletter this way:

// Assume success and create a new SentMessage to store and get permalink
$sent = new SentMessage();

$sent->setRecipients(/* ... */);
$sent->setSubject(/* ... */);
$sent->setContent(/* ... */);

// Get the slug for the new sent message
$slug = $sent->getSlug(); // Like latest-product-offers-546343

// Construct the full URL
// e.g. http://mydomain.com/newsletter/view/latest-product-offers-546343

// Actually send a new email
$mailer->send(/* .. */);

How can i construct the full URL (domain + controller + action + slug) to include it in a new email?

j0k
  • 22,600
  • 28
  • 79
  • 90
gremo
  • 47,186
  • 75
  • 257
  • 421

3 Answers3

55

With the router, of course

By default, the router will generate relative URLs (e.g. /blog). To generate an absolute URL, simply pass true to the third argument of the generate() method:

Perhaps your code might look like this

Symfony2

$url = $router->generate(
    'slug_route_name',
    array('slug' => $sent->getSlug()),
    true // This guy right here
);

Symfony3

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

$url = $router->generate(
    'slug_route_name',
    array('slug' => $sent->getSlug()),
    UrlGeneratorInterface::ABSOLUTE_URL // This guy right here
);
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • 3
    Amazing. So long time to learn Sf2 and never heard about full url generation. Thanks Peter, you always help us. – gremo May 16 '12 at 15:28
16

Update with Symfony 3:

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

$this->generateUrl('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL);
// http://www.example.com/blog/my-blog-post
ArGh
  • 1,148
  • 1
  • 11
  • 20
7

TWIG

If this is within a twig template, use url('your route') instead of path('your route') to get the absolute URL.

Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
Shairyar
  • 3,268
  • 7
  • 46
  • 86