你们中的任何一个 symfony2 大师都可以告诉我如何从 symfony2 服务中写一个 flash 消息吗?
当我如下注入容器时,我以为我有我需要的东西,但显然没有,我收到错误
Fatal error: Call to undefined method appDevDebugProjectContainer::getRequest() in /var/www/cloudsign_beta/src/BizTV/CommonBundle/Helper/globalHelper.php on line 135
所以显然我无法访问请求......如果我也必须从控制器传递它,我很快就会失去服务的意义,它本身无法做任何事情=)
<?php
namespace BizTV\CommonBundle\Helper;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManager as EntityManager;
use BizTV\CommonBundle\Entity\Log;
class globalHelper {
private $container;
private $em;
public function __construct(Container $container, EntityManager $em) {
$this->container = $container;
$this->em = $em;
}
public function log($type,$message) {
// currently $type can be 'success', 'fail' or 'error'.
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$currentCompany = $this->container->get('security.context')->getToken()->getUser()->getCompany();
//if the $type is one that we want to write to the log then create log entity (we don't log failed attempts at operations, but we do log errors.
if ($type == 'success') {
$em = $this->em;
$now = new \DateTime("now");
$entity = new Log();
$entity->setCompany($currentCompany);
$entity->setExecutor($currentUser);
$entity->setTime($now);
$entity->setEventType($type);
$entity->setEventMessage($message);
$em->persist($entity);
$em->flush();
}
//flash out the $message message text
$container = $this->container;
$session = $container->getRequest()->getSession()->setFlash($type, $message);
}
}