Php 如何使用Symfony访问细枝扩展中的全局服务功能?
我想有一个全局函数,它可以在所有控制器中使用,也可以在细枝扩展中使用。 该函数当前看起来如下所示:Php 如何使用Symfony访问细枝扩展中的全局服务功能?,php,symfony,twig,Php,Symfony,Twig,我想有一个全局函数,它可以在所有控制器中使用,也可以在细枝扩展中使用。 该函数当前看起来如下所示: namespace Symfony\Bundle\FrameworkBundle\Controller; class BaseController extends Controller { /** * Check if the user is assigned to one of the given airlines * * @param Array $airlines * * @r
namespace Symfony\Bundle\FrameworkBundle\Controller;
class BaseController extends Controller {
/**
* Check if the user is assigned to one of the given airlines
*
* @param Array $airlines
*
* @return boolean
*/
public function HAS_AIRLINE(Array $airlines) {
if ($airlines == null)
return false;
// Get current user
$user = $this->get('security.context')->getToken()->getUser();
foreach ($airlines as $airline) {
if($user->hasAirline($airline))
return true;
}
return false;
}
我在BaseController.php中实现了这个函数,因此我可以在所有其他控制器中使用它。到目前为止,这一切都很好。
现在我想在细枝扩展中也使用这个函数,但我不知道如何使用。我的小枝扩展中有以下功能:
/*
* Check if the current user has one of the given roles by using the function provided by the base controller
*/
public function hasAirline($airlines= Array())
{
if($airlines == null)
return false;
// How can I now use the function from my BaseController?
return HAS_AIRLINE($airlines);
}
我已经尝试将BaseController定义为服务,并在twig扩展中使用该服务,但我无法管理它
谁能帮帮我吗?我觉得Symfony有些东西我还不了解,但是这些文档并没有真正帮助我
谢谢,,
MRE您可以移动
用户
实体中的逻辑:
class User
{
public function hasAirline($airlines)
{
foreach ($airlines as $airline)
{
if ($this->getAirlines()->contains($airline))
{
return true;
}
}
return false;
}
}
如果getAirlines()
从Doctrine2返回ArrayCollection
,这将起作用,这允许使用该方法
然后,您可以在控制器中使用:
public function HAS_AIRLINE(Array $airlines) {
return $this->get('security.context')->getToken()->getUser()
->hasAirline($airlines);
}
或在树枝上:
{{ set hasAirline = app.user.hasAirline(airlines) }}