22

我将使用 Symfony2 定期向许多用户发送时事通讯。对于那些在使用电子邮件客户端阅读时遇到问题的人,我必须包含一个指向 HTML 电子邮件的永久链接。

无论如何,假设我以这种方式发送时事通讯:

// 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(/* .. */);

如何构建完整的 URL(域 + 控制器 + 操作 + slug)以将其包含在新电子邮件中?

4

3 回答 3

54

当然是路由器

默认情况下,路由器会生成相对 URL(例如/blog)。要生成绝对 URL,只需传递truegenerate()方法的第三个参数:

也许您的代码可能看起来像这样

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
);
于 2012-05-16T15:16:04.063 回答
16

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
于 2016-03-09T22:26:46.950 回答
7

枝条

如果这是在 twig 模板中,请使用url('your route')而不是path('your route')获取绝对 URL。

于 2015-01-13T11:14:16.867 回答