2016-11-10 1 views
1

シーンは、クライアント(私のサイトのAjaxのようなすべてのリクエスト)は、とjson_decodeでそれを受け取るように、{"token":"mytoken"} .PHPのようなjsonの文字列を要求します。私は$dataという名前の変数に格納するので、どのコントローラでも取得できます。symfonyでは、どのコントローラでグローバルメソッドと変数を取得できますか?

また、私はそれをサーバーにをregことができますが、私はその$this->get('input')->input($mykey);ようにそれを使用し、これは任意のコントローラに表示されますが、キーによってその

public function input($key, $default = '', $func = '') 
{ 
    $ret = ''; 
    if (isset($this->data[$key])) { 
     $ret = $this->data[$key]; 
    } else { 
     return $default; 
    } 
    if (is_string($func)) { 
     if (in_array($func, ['int', 'string', 'array'])) { 
      settype($ret, $func); 
      return $ret; 
     } 
     if ($func) 
      $ret = call_user_func($func, $ret); 
    } elseif (is_array($func)) { 
     if ($func) 
      $ret = call_user_func_array($func, [$ret]); 
    } 
    if (!$ret) 
     return $default; 
    return $ret; 
} 

のようなコードを値を取得するメソッドを作成します。これは提案された解決策ですか? 質問はちょうど私のタイトル、どのように?私を救いなさい。

答えて

1

JSONを解析し、結果オブジェクトを要求オブジェクトに設定するリクエストイベントリスナーを追加することを検討してください。実装例:

<?php 

use Symfony\Component\HttpKernel\Event\GetResponseEvent; 

class ParseJsonRequestListener 
{ 
    public function onKernelRequest(GetResponseEvent $event) 
    { 
     $request = $event->getRequest(); 

     // only parse the content body if the content type is JSON 
     if (preg_match('/\bjson\b/', $request->getContentType())) { 
      $parameters = json_decode($request->getContent(), true); 

      if ($parameters) { 
       $request->request->replace($parameters); 
      } 
     } 
    } 
} 

アプリ/設定/ services.ymlで、たとえば、リスナーを登録します。

parse_json_request_listener: 
    class: ParseJsonRequestListener 
    tags: 
     - { name: kernel.event_listener, event: kernel.request } 

今JSON要求を受けた任意のコントローラでは、あなたはから解析されたJSONデータを取得することができます要求は、たとえば:

<?php 

$token = $request->request->get('token'); 
+0

ありがとうございました!それは私の混乱、thkuに最適です –

0

方法はコントローラである場合は、のparamsに$ requestオブジェクトを追加することができます。

use Symfony\Component\HttpFoundation\Request; 
//... 
public function input(Request $request, $key, $default = '', $func = '') 
//... 

RequestオブジェクトはすべてグローバルVARSを持っています。詳細情報:http://symfony.com/doc/current/introduction/http_fundamentals.html#symfony-request-object

+0

大変です、ありがとう! –

関連する問題