LoginSignup
4
7

More than 3 years have passed since last update.

SlimでJSONを返すところまでメモ

Last updated at Posted at 2019-08-25

概要

PHPの軽量フレームワークであるSlimを触ってみたのでメモ。
WebAPIを実装してレスポンスとしてJSONを返すところまで。

環境

macOS 10.13.6
PHP 7.1.23
composer 1.8.0
Slim 4.0.0

インストール

公式サイトに載っている手順に従ってインストールを行なっていきます。

$ mkdir slim-test
$ cd slim-test
$ composer require slim/slim:4.0.0
$ composer require slim/psr7

これで最低限のインストールは完了です。

動作確認

Hello worldを表示する

現状のディレクトリ構成は下記のようになっているはずですので、slim-test以下にpublicディレクトリを作成し、index.phpを記述していきます。

.
├── composer.json
├── composer.lock
└── vendor
    ├── autoload.php
    ├── composer
・・・省略・・・
$ mkdir public
$ vi public/index.php
index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $response->getBody()->write("Hello world!");
    return $response;
});

$app->run();

記述したら下記コマンドを実行してブラウザで「localhost:8080」にアクセスするとHello world!とだけ記載されたページが確認できます。

$ php -S localhost:8080 -t public
PHP 7.1.23 Development Server started at Sun Aug 25 15:27:28 2019
Listening on http://localhost:8080
Document root is /path/to/slim-test/public
Press Ctrl-C to quit.

スクリーンショット 2019-08-25 15.41.24.png

JSONを返す

現状だと「Hello world!」という文字列を返しているだけですので、JSONを返すように修正します。
※Slimのv3とv4で書き方が異なるので注意してください。

index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $data = array('response' => 'Hello world!');
    $payload = json_encode($data);
    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();

先程と同様にブラウザでアクセスするかcurlコマンドを実行してレスポンスを確認する。

スクリーンショット 2019-08-25 16.28.53.png

$ curl localhost:8080
{"response":"Hello world!"}

これで、リクエストに対してJSONを返すことができました。

パラメータを受け取る

レスポンスを固定で返しているので、受け取ったパラメータを反映させてみます。

index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $params = $request->getQueryParams();
    $data = array('response' => 'Hello '.$params['name']);
    $payload = json_encode($data);
    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();
$ curl localhost:8080?name=hogehoge
{"response":"Hello hogehoge"}

最終的なディレクトリ構成

.
├── README.md
├── composer.json
├── composer.lock
├── public
│   └── index.php
└── vendor
    ├── autoload.php
    ├── composer
・・・省略・・・

感想

お手軽にWebAPIを実装できる点は素晴らしかったです。JSONを返す書き方がv3とv4で違った点でちょっと躓いたので、バージョンの差異には注意しないといけませんでした。
備忘録的に書いていますので、もっとこうした方が良いとか内容間違っているとかありましたらご指摘下さい。

参考サイト

4
7
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
4
7