LoginSignup
54
59

More than 5 years have passed since last update.

cakePHP3でAPIを叩く!

Posted at

cakePHP3でAPI叩きたい!

cakePHP3でAPI叩きたくないですか?
しかもajax使って。

jquery使う?

最初はjqueryだけを使おうかなって思ってたんですけど、クロスドメインの問題があるということと、APIを叩くためのtokenが必要で、それをhtmlの中に書きたくないなぁということで、
cakePHP3のサーバサイドでAPIを叩き、jqueryを使ってcakePHP3が叩いたAPIの結果をjsonで取得するという方法にしてみました。

cakePHP3でjsonを返す

SIMPLE JSON RESPONSE WITH CAKEPHP 3を見ると良いと思います。

コードはこんな感じ。

controller
namespace App\Controller;

class MyCustomersController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function customers()
    {
        $customers['id'] = '123';
        $this->set('customers', $customers);
        $this->set('_serialize', ['customers']);
    }
}

これで、getJSON()すれば大丈夫です。

<script>
$(function() {
    $.getJSON('/mycustomers/customers',
        null,
        function(data, status) {
            console.log(data);
        }
    );
});
</script>

cakePHP3でAPIを叩く!

まぁ、ここがメインというか・・。

"php", "API", "叩く"とかでググると出てきますよね、file_get_contents()。
ふんふんなるほど。
そして、正しく取得できたかどうかを$http_response_headerを見て・・・。

何か、かなり原始的な処理を書こうとしている予感(´・ω・`)
Requestクラスとか、Responseクラスとか、そういうのあると思うんですよ、cakeにも。

というわけで調べたら、ありました、Clientクラス
使い方は簡単!

$http = new Client();
$response = $http->get('http://hogehoge.com');

jsonが返ってくるようなAPIであれば、さらにこうすると良いと思います。

if ($http->isOk) {
    $json = json_decode($response->body());
}

詳しくは公式Referenceをチェケラ(・ω<)

54
59
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
59