我正在研究Symfony 2.7 WebApp。我创建的其中一个包包括一个提供一些用户相关内容的服务,例如userHasPurchases()
。
问题是,包括Twig Extesion
在内的其他服务会破坏:
AppShopService
namespace AppShopBundle\Service;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
...
class AppShopService {
protected $user;
public function __construct(TokenStorageInterface $tokenStorage, ...) {
$this->user = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null;
...
}
public function userHasPurchases(User $user) {
$user = $user ? $user : $this->user;
$result = $user...
return result;
}
}
AppShopBundle \资源\配置\ services.yml
services:
app_shop.service:
class: AppShopBundle\Service\AppShopService
arguments:
- "@security.token_storage"
- ...
到目前为止一切正常:AppShopServices
是使用当前用户创建的,userHasPurchases()
按预期工作。
现在我添加了 Twig Extension ,以便能够在我的模板中使用userHasPurchases()
:
Twig Extension
namespace AppShopBundle\Twig;
use AppShopBundle\Service\AppShopService;
class AppShopExtension extends \Twig_Extension {
private $shopService;
public function __construct(AppShopService $shopService) {
$this->shopService = $shopService;
}
public function getName() {
return 'app_shop_bundle_extension';
}
public function getFunctions() {
$functions = array();
$functions[] = new \Twig_SimpleFunction('userHasPurchases', array(
$this,
'userHasPurchases'
));
return $functions;
}
public function userHasPurchases($user) {
return $this->shopService->userHasPurchases($user);
}
}
在AppShopBundle \ Resources \ config \ services.yml中包含扩展程序
services:
app_shop.service:
class: AppShopBundle\Service\AppShopService
arguments:
- "@security.token_storage"
- ...
app_shop.twig_extension:
class: AppShopBundle\Twig\AppShopExtension
arguments:
- "@app_shop.service"
tags:
- { name: twig.extension }
在列入Twig Extension
后,AppShopService
及其方法userHasPurchases
不再有效。问题是,AppShopService
的构造函数不再设置user
,因为$tokenStorage->getToken()
现在返回null
。
这怎么可能?除了Twig Extension
之外,我什么都没改变。我从Twig Extension
移除services.yml
后,一切正常。
我唯一的猜测是,Twig Extension
的创建是在任何安全性之前完成的。但为什么呢?
知道这里可能有什么问题吗?
答案 0 :(得分:3)
不要在构造函数中与tokenStorage进行交互,而只能在userHasPurchases
方法中进行交互。
namespace AppShopBundle\Service;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
...
class AppShopService {
protected $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage, ...) {
$this->tokenStorage = $tokenStorage;
}
public function userHasPurchases(User $user) {
$user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
$result = $user...
return result;
}
}
希望这个帮助