Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access service container in symfony2 global helper function (service)?
    primarykey
    data
    text
    <p>This question started out with me not understanding why I couldn't pass variables to a symfony2 global helper function (service), but thanks to people brighter than I, I realized my error was about trying to use the security_context from within a class that didn't have it injected so...</p> <p>This is the final result, the code that works. I found no better way of making this helpful to the comunity.</p> <p>This is how you can get the user and other data from security_context from within a global function or helper function in symfony2.</p> <p>I have the following class and function:</p> <pre><code>&lt;?php namespace BizTV\CommonBundle\Helper; use Symfony\Component\DependencyInjection\ContainerInterface as Container; class globalHelper { private $container; public function __construct(Container $container) { $this-&gt;container = $container; } //This is a helper function that checks the permission on a single container public function hasAccess($container) { $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser(); //do my stuff } } </code></pre> <p>...defined as a service (in app/config/config.yml) like this...</p> <pre><code>#Registering my global helper functions services: biztv.helper.globalHelper: class: BizTV\CommonBundle\Helper\globalHelper arguments: ['@service_container'] </code></pre> <p>Now, in my controller I call on this function like this...</p> <pre><code>public function createAction($id) { //do some stuff, transform $id into $entity of my type... //Check if that container is within the company, and if user has access to it. $helper = $this-&gt;get('biztv.helper.globalHelper'); $access = $helper-&gt;hasAccess($entity); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload