[Symfony] Customize with Symfony
Customize with Symfony
Symfony Event
<?php
namespace Customize\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class HelloListener implements EventSubscriberInterface
{
public function onResponse(FilterResponseEvent $event)
{
echo 'hello world'; // Method 詳細
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onResponse', // Event名・Method 追加
];
}
}
### Use Entity Manager in Listener
namespace MPN\CRMBundle\Manager;
use Doctrine\ORM\EntityManager;
use MPN\CRMBundle\Entity\Analytics;
use MPN\CRMBundle\Service\DateTimeBuilder;
class AnalyticsManager
{
/**
* @var EntityManager
*/
public $em;
/**
* @var DateTimeBuilder
*/
private $dateTimeBuilder;
/**
* @var array
*/
private $analytics;
public function __construct(EntityManager $em, DateTimeBuilder $dateTimeBuilder)
{
$this->em = $em; // EntityManager
$this->dateTimeBuilder = $dateTimeBuilder;
$this->setup();
}
/**
* Flushes the data to the database.
*
* @return void
*/
public function save()
{
$this->em->flush(); // 保存
}
}
Render in Listener
use Twig\Environment;
public $_engine;
public function __construct(\Swift_Mailer $mailer, Environment $engine)
{
$this->mailer= $mailer;
$this->_engine = $engine;
}
this->mailer->send( (new \Swift_Message('something happened'))
->setFrom('test@test.com')
->setTo('user@user.com')
->setBody($this->_engine->render('mails/test.html.twig',[
])
);
use Twig\Environment;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TwigInitializeListener implements EventSubscriberInterface
{
/**
* @var Environment
*/
protected $twig;
/**
* TwigInitializeListener constructor.
*
* @param Environment $twig
*/
public function __construct(
Environment $twig,
) {
$this->twig = $twig;
}
- send var to view from event listener ~~~~php $this->twig->addGlobal(‘Page’, $Page);
$this->twig->render( ‘Entry/confirm.twig’, [ ‘form’ => $form->createView(), ] ); ~~~~