2012年6月21日木曜日

symfony2を読む(3)

さて、前回に引き続きsymfony2を読み解く。今日は以下の箇所について調べる。

./web/app_dev.php


[php]
Request::createFromGlobals()
[/php]

vendor/symfony/src/Symfony/Component/HttpFoundation/Request.php


[php]
static public function createFromGlobals()
{
$request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);

if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE'))
) {
parse_str($request->getContent(), $data);
$request->request = new ParameterBag($data);
}

return $request;
}
[/php]
1行目, new static ってなんだ!? new self と new static の違い - Sarabande.jp によると、記述元のクラスでメソッド呼び出された風になるのが、new self, 呼び出し元のクラスでメソッド呼び出し風になるのが new static とのことだが、今回は記述元も呼び出し元も同じである。例えばJavaでstatic int といえばすべてのインスタンスで共有したいintを指すが、今回は他のクラスからRequestインスタンスを呼び出すときに同一のものを扱いたい、ということなのだろうか?そういうことにしておこう。何はともあれ、コンストラクタの呼び出しがあり、そこで初期化のための関数が呼ばれる。
[php]
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->request = new ParameterBag($request);
$this->query = new ParameterBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new ParameterBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders());

$this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}
[/php]
ここではキーと値を格納するクラスParameterBagのインスタンスが内部変数に格納される。createFromGlobalsに戻ろう。
[php]
if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE'))
) {
parse_str($request->getContent(), $data);
$request->request = new ParameterBag($data);
}
[/php]
if文の中には

  1. ファイルアップロードで使われるようなCONTENT_TYPEではない。

  2. PUT OR DELETE メソッド


の2つを満たす時にだけ入る。このとき、リクエストの内容はrequestBodyに書き換えられる。

最後に Requestクラスのstaticインスタンスを返して終了だ。

0 件のコメント:

コメントを投稿