And*_*ord 5 php symfony twig twig-extension
我正在研究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;
}
}
Run Code Online (Sandbox Code Playgroud)
AppShopBundle \资源\设置\ services.yml
services:
app_shop.service:
class: AppShopBundle\Service\AppShopService
arguments:
- "@security.token_storage"
- ...
Run Code Online (Sandbox Code Playgroud)
到目前为止一切正常:AppShopServices使用当前用户创建userHasPurchases()并按预期工作.
现在我添加了一个Twig扩展,以便能够userHasPurchases()在我的模板中使用:
树枝延伸
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在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 }
Run Code Online (Sandbox Code Playgroud)
在结束之后Twig Extension,AppShopService它的方法userHasPurchases不再起作用了.问题是,自从现在返回后,构造函数AppShopService不再设置.user$tokenStorage->getToken()null
这怎么可能?我没有改变,除了包括Twig Extension.当我删除Twig Extension从services.yml一切又正常工作.
我唯一的猜测是,Twig Extension在任何安全性之前完成创建.但为什么?
知道这里可能有什么问题吗?
不要在构造函数中与 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;
}
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助