[PHP]超入門!! Guzzleの使い方チュートリアル

カテゴリ: composer, GuzzleHttp, PHP

この記事では、PHPでHttp通信を行うためのコンポーネントである、Guzzleを使うための手順を説明します。PHPに慣れていない人のために、PHPのパッケージマネージャであるcomposerのインストールから説明しています。

確認環境環境のインストール

今回はvagrant上にて、こちらの手順でCentOS7.3+PHP7.1の環境を用意しています。

Composerのインストール

まずは、PHPのパッケージマネージャーであるComposerをインストールします。Composerを使うする理由は、Guzzleコンポーネントはcomposerでインストールするのが最も簡単なためです。

Composerのオフィシャルサイト(https://getcomposer.org/download/)に記載の通り、下記のコマンドでインストールが可能です。

色々やってそうに見えますが、https://getcomposer.org/installerからphpスクリプトをダウンロードして実行しているだけです。

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

実行するとカレントディレクトリにcomopser.pharができます。php composer.pharコマンドを実行して、下記のようにヘルプが出ればよいです。

$ php composer.phar
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.5.2 2017-09-11 16:59:25

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
...

Linuxの場合、下記のように/usr/local/binへコピーしておくと、composerコマンドだけで実行できるので便利です。

$ sudo mv composer.phar /usr/local/bin/composer

$ composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.5.2 2017-09-11 16:59:25

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
...

あと、composerはgitコマンドを使う(事が多い)ので、gitのクライアントもインストールしておきます。

sudu yum install git -y

Loaded plugins: fastestmirror
You need to be root to perform this command.
[vagrant@localhost vagrant]$ sudo yum install git -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: www.ftp.ne.jp
 * epel: ftp.kddilabs.jp
...
Installed:
  git.x86_64 0:1.8.3.1-12.el7_4


Dependency Installed:
  libgnome-keyring.x86_64 0:3.12.0-1.el7   perl-Error.noarch 1:0.17020-2.el7   perl-Git.noarch 0:1.8.3.1-12.el7_4   perl-TermReadKey.x86_64 0:2.30-20.el7
  rsync.x86_64 0:3.0.9-18.el7

Complete!

yum installコマンドが完了したら、gitがインストールできたことを確認します。

$ git --version
git version 1.8.3.1

Guzzleをインストールする

guzzleモジュールのインストールは、composerのrequireコマンドを使用します。

$ composer require guzzlehttp/guzzle

Using version ^6.3 for guzzlehttp/guzzle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
    Failed to download guzzlehttp/promises from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /etc/php.ini
    Now trying to download from source
  - Installing guzzlehttp/promises (v1.3.1): Cloning a59da6cf61
    Failed to download psr/http-message from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /etc/php.ini
    Now trying to download from source
  - Installing psr/http-message (1.0.1): Cloning f6561bf28d
    Failed to download guzzlehttp/psr7 from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /etc/php.ini
    Now trying to download from source
  - Installing guzzlehttp/psr7 (1.4.2): Cloning f5b8a8512e
    Failed to download guzzlehttp/guzzle from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /etc/php.ini
    Now trying to download from source
  - Installing guzzlehttp/guzzle (6.3.0): Cloning f4db5a78a5
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
Writing lock file
Generating autoload files

コマンドの実行後、lsコマンドで、composer.json、composer.lockファイルと、vendorディレクトリが出来ていることを確認します。

$ ls -al

drwxrwxrwx.  1 vagrant vagrant 4096 Oct  9 07:29 .
dr-xr-xr-x. 18 root    root     239 Oct  9 05:58 ..
-rwxrwxrwx.  1 vagrant vagrant   63 Oct  9 07:28 composer.json
-rwxrwxrwx.  1 vagrant vagrant 8209 Oct  9 07:29 composer.lock
drwxrwxrwx.  1 vagrant vagrant    0 Oct  9 07:29 vendor

composer showコマンドで、インストールされたパッケージ一覧を確認します。今回の例では、version6.3.0がインストールされました。guzzlehttp/guzzle以外にも、guzzlehttp/promises等のパッケージが入っていいますが、これはguzzlehttp/guzzleが内部的に使用している依存パッケージです。
※依存関係が気になる人は、cat vendor/guzzlehttp/guzzle/composer.jsonコマンドを実行してみると、もう少し詳しい情報を知ることができます。

$ composer show

guzzlehttp/guzzle   6.3.0  Guzzle is a PHP HTTP client library
guzzlehttp/promises v1.3.1 Guzzle promises library
guzzlehttp/psr7     1.4.2  PSR-7 message implementation that also provides common utility methods
psr/http-message    1.0.1  Common interface for HTTP messages

guzzleの動作確認

コンポーネントがインストール出来たら動作確認を行います。
今回は、自分のグローバルIPが確認できるサイト、http://ifconfig.co/を利用してみます。

下記のコードで、http://ifconfig.co/ipへアクセスし、応答ステータスと、結果の本文(body)を取得することができます。
(http://ifconfig.co/を使った事がない場合場合は、上記のURLへブラウザからアクセスし、何が返ってくるか確認してみてください)

<?php
require_once 'vendor/autoload.php';

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://ifconfig.co/ip');

echo $res->getStatusCode() . PHP_EOL;
echo $res->getBody() . PHP_EOL;

上記のファイルを、catコマンドを使って作成します。
(もちろんviコマンドでファイルを編集したり、手元のPCでファイルを作成後SCPでファイル転送しても大丈夫です)

cat <<'EOT' > guzzle_test.php 
<?php
require_once 'vendor/autoload.php';

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://ifconfig.co/ip');

echo $res->getStatusCode() . PHP_EOL;
echo $res->getBody() . PHP_EOL;
EOT

このファイルを実行すると、以下のようにステータスコード=200と、自分のグローバルIPが取得できます。

$ php guzzle_test.php
200
143.11.23.1

これで、インストールしたGuzzleコンポーネントが使えることが分かりました。


Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です