I'd like to have a global function which is available in all controllers as well as in a twig extension. The function currently looks like this:
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;
}
I implemented this function into the BaseController.php, so I can use it in all other controllers. This works perfectly fine so far. Now I want to use this function in a twig extension as well, but I don't know how. I do have the following function in my twig extension:
/*
* 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);
}
I already tried to define the BaseController as a service and use the service in the twig extension, but I couldn't manage that.
Could someone please help me? I feel like there is something I did not understand about Symfony yet, but the docs do not really help me.
Thank you, MRE
You can move the logic in your User
entity:
class User
{
public function hasAirline($airlines)
{
foreach ($airlines as $airline)
{
if ($this->getAirlines()->contains($airline))
{
return true;
}
}
return false;
}
}
This will work if getAirlines()
return an ArrayCollection
from Doctrine2, this allow the use of the contains()
method.
Then you can use this in the controller:
public function HAS_AIRLINE(Array $airlines) {
return $this->get('security.context')->getToken()->getUser()
->hasAirline($airlines);
}
Or in Twig with app.user
:
{{ set hasAirline = app.user.hasAirline(airlines) }}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments