[英]Getting session issue in Service class files in symfony
我正在使用symfony2,并且在Service容器文件中,使用会话存在问题。
这是我的服务文件:
public function FinalPrice()
{
$session = $this->get('Currency');
return $session;
}
我在类的顶部灌入了Response和Session库:
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
我在symfony网站上找到了它,可以轻松地在这里正常使用它
http://symfony.com/doc/current/book/service_container.html
其中说:
public function indexAction($bar)
{
$session = $this->get('session');
$session->set('foo', $bar);
// ...
}
但我收到此错误:
FatalErrorException: Error: Call to undefined method Doobin\CoreBundle\service\GeneralClass::get() in /var/www/doobin92/src/Doobin/CoreBundle/service/GeneralClass.php line 311
我也尝试过:
$session = $this->getRequest()->getSession();
但是它给出了这个错误:
FatalErrorException: Error: Call to undefined method Doobin\CoreBundle\service\GeneralClass::getRequest() in /var/www/doobin92/src/Doobin/CoreBundle/service/GeneralClass.php line 311
预先感谢您
您在此处尝试使用的get()
和getRequest()
帮助器是Symfony2基本Controller的一部分。
一旦您的控制器扩展了上面显示的基本控制器,就应仅在Controller上下文中使用它们。
如果看一下代码,您可能会注意到他们两个都使用container
来获取getRequest()
的request_stack
服务;
$this->container->get('request_stack')->getCurrentRequest();
以及任何其他get()
服务,
$this->container->get($id);
当您尝试在服务中调用这两个方法时。 你在一个控制器上下文不是和您要添加的服务类不提供这样的帮手。
为了解决这个问题,
您必须将要通过get()
帮助程序调用的服务直接插入服务中,或者,
通过添加来注入容器,
use Symfony\Component\DependencyInjection\ContainerInterface;
public YourServiceClass
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
到您的服务等级,
和,
your_service_id:
class: YourServiceClass
arguments: ["@service_container"]
您的服务定义。
一种方法是将服务容器注入您的服务。
services:
your_service:
class: YourClass
arguments: ["@service_container"]
在您的服务类别中:
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
YourClass {
protected $container;
public function __construct(Container $container) {
$this->container = $container;
}
}
然后,您可以使用$this->container->get('session');
在您的服务中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.