Symfony 如何将细枝服务添加到我的捆绑包中?
我创建了一个新的bundle(AcmeNotificationBundle),我想将其作为如下服务使用:Symfony 如何将细枝服务添加到我的捆绑包中?,symfony,twig,Symfony,Twig,我创建了一个新的bundle(AcmeNotificationBundle),我想将其作为如下服务使用: $notification = $this->get( 'notification' ); $mess = $notification->getNotification( 'Some notification message' )->createView(); 但在我的包中,我需要一个细枝服务来呈现通知模板。我知道在Resources\config\services.ym
$notification = $this->get( 'notification' );
$mess = $notification->getNotification( 'Some notification message' )->createView();
但在我的包中,我需要一个细枝服务来呈现通知模板。我知道在Resources\config\services.yml文件中需要类似的内容:
services:
twig:
class: Path\To\Twig\Class
但我不知道怎样才能上twig课。Аnyone遇到了这个问题?向捆绑包中添加细枝服务的正确方法是什么?您的捆绑包中已经提供了模板服务。您可以从容器中检索它:
$container->get('templating');
您应该能够以类似的方式访问细枝服务:
$container->get('twig');
我的回答的其余部分使用模板服务,但如果您真的需要,您可以很容易地将其替换为细枝
我认为您需要的是将模板服务传递给通知服务
services:
notification:
class: Acme\NotificationBundle\Notification
arguments: [@templating]
通知类将模板作为构造函数参数:
use Symfony\Bundle\TwigBundle\TwigEngine;
class Notification
{
/**
* @var Symfony\Bundle\TwigBundle\TwigEngine $templating
*/
private $templating = null;
/**
* @param Symfony\Bundle\TwigBundle\TwigEngine $templating
*
* @return null
*/
public function __construct(TwigEngine $templating)
{
$this->templating = $templating;
}
}
与$notification->getNotification('Some notification message')->createView()
不同,我可能会执行$notification->createNotificationView('Some notification message')
。我假设通知消息是一个实体,不需要将模板传递给该实体
相关文档:您的捆绑包中已经提供了模板服务。您可以从容器中检索它:
$container->get('templating');
您应该能够以类似的方式访问细枝服务:
$container->get('twig');
我的回答的其余部分使用模板服务,但如果您真的需要,您可以很容易地将其替换为细枝
我认为您需要的是将模板服务传递给通知服务
services:
notification:
class: Acme\NotificationBundle\Notification
arguments: [@templating]
通知类将模板作为构造函数参数:
use Symfony\Bundle\TwigBundle\TwigEngine;
class Notification
{
/**
* @var Symfony\Bundle\TwigBundle\TwigEngine $templating
*/
private $templating = null;
/**
* @param Symfony\Bundle\TwigBundle\TwigEngine $templating
*
* @return null
*/
public function __construct(TwigEngine $templating)
{
$this->templating = $templating;
}
}
与$notification->getNotification('Some notification message')->createView()
不同,我可能会执行$notification->createNotificationView('Some notification message')
。我假设通知消息是一个实体,不需要将模板传递给该实体
相关文档:感谢您快速、完整的回答!这正是我需要的!谢谢你的快速和有帮助的回答!这正是我需要的!我认为这是一个更好的答案:[10304468][我认为这是一个更好的答案:[10304468][