この質問は、変数を symfony2 のグローバル ヘルパー関数 (サービス) に渡すことができない理由を理解していないことから始まりましたが、私より頭の良い人たちのおかげで、私のエラーは、セキュリティ コンテキストを渡さないクラス内から security_context を使用しようとしたことであることに気付きました。注射はしないので...
これが最終結果であり、機能するコードです。これをコミュニティに役立てるためのより良い方法は見つかりませんでした。
これは、symfony2 のグローバル関数またはヘルパー関数内から security_context からユーザーおよびその他のデータを取得する方法です。
私は次のクラスと関数を持っています:
<?php
namespace BizTV\CommonBundle\Helper;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class globalHelper {
private $container;
public function __construct(Container $container) {
$this->container = $container;
}
//This is a helper function that checks the permission on a single container
public function hasAccess($container)
{
$user = $this->container->get('security.context')->getToken()->getUser();
//do my stuff
}
}
...このように(app/config/config.ymlで)サービスとして定義されています...
#Registering my global helper functions
services:
biztv.helper.globalHelper:
class: BizTV\CommonBundle\Helper\globalHelper
arguments: ['@service_container']
さて、コントローラーでこの関数を次のように呼び出します...
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->get('biztv.helper.globalHelper');
$access = $helper->hasAccess($entity);