Symfony2 - コントローラーで__construct()を使用してSecurty.Contextにアクセスするにはどうすればいいですか? 質問する

Symfony2 - コントローラーで__construct()を使用してSecurty.Contextにアクセスするにはどうすればいいですか? 質問する

Symfony2 で問題があります。具体的には、__construct() 関数の使い方です。公式ドキュメントは驚くほどひどいです。

以下のものを使用できるようにしたいです:

public function __construct()
{
    parent::__construct();
    $user = $this->get('security.context')->getToken()->getUser();
}

しかし、次のエラーが発生します:

致命的なエラー: /Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php の 11 行目でコンストラクタを呼び出すことができません

11行目は「parent::__construct();」です。

削除したら、次の新しいエラーが発生しました

致命的なエラー: /Sites/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php の 242 行目で、非オブジェクトに対してメンバー関数 get() を呼び出しました

考えるContainerInterface DIC を設定する必要があるかもしれませんが、その方法がわかりません (試してみましたが、惨めに失敗しました)

皆さん何かアイデアはありますか?

アップデート- ContainerAware を拡張するように変更しようとしましたが、次のエラーが発生しました:

致命的なエラー: クラス DEMO\DemoBundle\Controller\Frontend\HomeController は、/Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php の 43 行目で、Symfony\Component\DependencyInjection\ContainerAwareInterface インターフェイスから拡張できません。

コントローラーで次のコードを使用します。

<?php

namespace DEMO\DemoBundle\Controller\Frontend;

use Symfony\Component\DependencyInjection\ContainerAware;

class HomeController extends ContainerAwareInterface
{
     protected $container;

     public function setContainer(ContainerInterface $container = null)
     {
         $this->container = $container;
     }

ベストアンサー1

デフォルトの Symfony コントローラーを拡張していると思いますか? もしそうなら、コードを見れば答えがわかります:

namespace Symfony\Bundle\FrameworkBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;

class Controller extends ContainerAware
{

Controller::__construct が定義されていないので、parent::__construct を使用しても何も起こらないことに注意してください。ContainerAware を見てみましょう。

namespace Symfony\Component\DependencyInjection;

class ContainerAware implements ContainerAwareInterface
{
    protected $container;
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}

繰り返しますが、コンストラクターはなく、setContainer が呼び出されるまでコンテナーは使用できません。したがって、setContainer をオーバーライドして、そこにロジックを配置します。または、ベース コントローラー クラスを拡張しないスタンドアロン コントローラーを作成し、依存関係をコンストラクターに直接挿入します。

2017年8月更新

これについては、まだいくつかヒットしています。各コントローラーの前に何かを実行したい場合は、カーネル コントローラー リスナーを使用します。必要なのがユーザーだけの場合は、もちろん getUser() を使用します。また、setContainer() をオーバーライドしないでください。場合によっては機能しますが、コードが複雑になるだけです。

おすすめ記事