2012-10-25 15 views
18

Symfony2を使用して、HTTPSに基づく外部APIにアクセスする必要があります。私は外部のURIを呼び出し、それを「再生」する応答を管理するにはどうすればよいSymfony2 - 外部リクエストの実行方法

。たとえば、成功または失敗のメッセージを表示するには?

私は(performRequestが完全に発明された方法であることに注意してください)のようなもので考えています:

$response = $this -> performRequest("www.someapi.com?param1=A&param2=B"); 

if ($response -> getError() == 0){ 
    // Do something good 
}else{ 
    // Do something too bad 
} 

私はバズや他のクライアントについて読んでてきました。しかし、私はSymfony2がそれ自身でそれを行うことができるはずだと思います。

+0

どのような種類のリクエストですか?ちょうどHTTP GET? –

+0

GETまたはPOSTは知っておくと良いでしょう;) – ElPiter

答えて

25

私はCURLを使用することをお勧めしたい:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A&param2=B'); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // Assuming you're requesting JSON 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$response = curl_exec($ch); 

// If using JSON... 
$data = json_decode($response); 

注: Webサーバー上のPHPはphp5-curlライブラリをインストールする必要があります。 APIリクエストはJSONデータを返すと仮定すると

this pageは有用である可能性があります。

これはSymfony2に固有のコードを使用しません。このプロセスを簡素化できるバンドルがあるかもしれませんが、もし私がそれについて知りません。

+2

この例には 'Content-Type'ヘッダーの誤った使用が含まれています。リクエストで使用される場合、ボディのタイプを示します(これはあなたの例では使用されません)。サーバが返すタイプを指定するには、 'Accept'ヘッダを使用します。 'Accept:application/json'ヘッダ –

24

symfonyはこのための組み込みサービスを持っていませんが、これは依存性注入フレームワークを使用して、独自に作成するには絶好の機会です。ここでできることは、外部呼び出しを管理するサービスを作成することです。サービスを "http"と呼んでみましょう。

まず、performRequest()メソッドを持つクラスを記述します。

namespace MyBundle\Service; 

class Http 
{  
    public function performRequest($siteUrl) 
    { 
     // Code to make the external request goes here 
     // ...probably using cUrl 
    } 
} 

app/config/config.ymlでサービスとして登録します。

services: 
    http: 
     class: MyBundle\Service\Http 

を今すぐあなたのコントローラは、「HTTP」と呼ばれるサービスへのアクセスを持っています。 symfonyは「コンテナ」で、このクラスの単一のインスタンスを管理し、あなたは$this->get("http")経由でアクセスすることができます。

class MyController 
{ 
    $response = $this->get("http")->performRequest("www.something.com"); 

    ... 
} 
10

https://github.com/sensio/SensioBuzzBundleは、あなたが探しているもののようです。

これは、HTTPリクエストを実行するためにクリスWallsmithの話題ライブラリを実装しています。

私はあなたがgithubのページ上のドキュメントを読んでもらおう、使い方はかなり基本的なものです:

$buzz = $this->container->get('buzz'); 

$response = $buzz->get('http://google.com'); 

echo $response->getContent(); 
3

symfonyは自身の残りのクライアントを持っていませんが、あなたはすでに述べたようにバンドルのカップルがあります。この1は私のものを好まれる:

https://github.com/CircleOfNice/CiRestClientBundle

$restClient = $this->container->get('ci.restclient'); 

$restClient->get('http://www.someUrl.com'); 
$restClient->post('http://www.someUrl.com', 'somePayload'); 
$restClient->put('http://www.someUrl.com', 'somePayload'); 
$restClient->delete('http://www.someUrl.com'); 
$restClient->patch('http://www.someUrl.com', 'somePayload'); 

$restClient->head('http://www.someUrl.com'); 
$restClient->options('http://www.someUrl.com', 'somePayload'); 
$restClient->trace('http://www.someUrl.com'); 
$restClient->connect('http://www.someUrl.com'); 

あなたは

$response = $restclient->get($url); 

経由でリクエストを送信し、symfonyのレスポンスオブジェクトを取得します。 そして、あなたはあなたのコードは次のようになり

$httpCode = $response-> getStatusCode(); 

を経由してステータスコードを取得することができます:私は知っている

$restClient = $this->container->get('ci.restclient'); 
if ($restClient->get('http://www.yourUrl.com')->getStatusCode !== 200) { 
    // no error 
} else { 
    // error 
} 
12

ベストクライアントは、次のとおりです。http://docs.guzzlephp.org/en/latest/

ことがSymfony2の中にそれを統合するバンドルがすでにありますプロジェクト: https://github.com/8p/GuzzleBundle

$client = $this->get('guzzle.client'); 

// send an asynchronous request. 
$request = $client->createRequest('GET', 'http://httpbin.org', ['future' => true]); 
// callback 
$client->send($request)->then(function ($response) { 
    echo 'I completed! ' . $response; 
}); 

// optional parameters 
$response = $client->get('http://httpbin.org/get', [ 
    'headers' => ['X-Foo-Header' => 'value'], 
    'query' => ['foo' => 'bar'] 
]); 
$code = $response->getStatusCode(); 
$body = $response->getBody(); 

// json response 
$response = $client->get('http://httpbin.org/get'); 
$json = $response->json(); 

// extra methods 
$response = $client->delete('http://httpbin.org/delete'); 
$response = $client->head('http://httpbin.org/get'); 
$response = $client->options('http://httpbin.org/get'); 
$response = $client->patch('http://httpbin.org/patch'); 
$response = $client->post('http://httpbin.org/post'); 
$response = $client->put('http://httpbin.org/put'); 

詳細情報はhttp://docs.guzzlephp.org/en/latest/index.html

+0

GuzzleはPHP> = 5.5.0を必要としていることに注意してください。symfonyの必要条件(v5.3.3)より少し遅いです。 –

+0

GuzzleBundle githubページから: 要件PHP 5.4以上しかし、今度はGuzzle libにPHP> = 5.5.0が必要です。私はこれが私の答えから変わったと思う。 –

+0

ええ、これは最新のようではありませんが、私はGuzzleBundleリポジトリで修正するプルリクエストを提案しました。私はGuzzleとGuzzleBundleの両方の作者が最終的に答えを得るだろうと思っています:) +1とにかく、この優れたライブラリを知りませんでした。 –

関連する問題