![](/img/trans.png)
[英]How to use renderView and twig templating in a Symfony 4 Service
[英]Symfony Twig Extension breaks other service - Is templating done before security?
我正在研究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擴展 ,以便能夠在我的模板中使用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);
}
}
在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
之外,我什么都沒改變。 一旦我從services.yml
刪除了Twig Extension
,一切都能正常工作。
我唯一的猜測是, Twig Extension
的創建是在任何安全性之前完成的。 但為什么?
知道這里可能有什么問題嗎?
不要在構造函數中與tokenStorage進行交互,而只能在userHasPurchases
方法中進行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;
}
}
希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.