LoginSignup
2
1

More than 5 years have passed since last update.

PHPのjsonテンプレートjbuilder/commonを動かしてみる

Last updated at Posted at 2015-12-14

JBuilderを動かす

composerでライブラリをインストール

以下みたいな感じでcomposerを作成

composer.json
{
    name: jbuilderTest,
    require: {
        psy/psysh: ^0.6.1,
        jbuilder/common: ^1.0
    },
    authors: [
        {
            name: hoge,
            email: hogehoge@test.com
        }
    ]
}

composerでライブラリをインストール

$ composer install

psySHを起動し、公式に書いてある例からcommentsのオブジェクトを外して書いてみる

$ vendor/bin/psysh # composerでインストールしたライブラリはカレントディレクトリのvendor配下に入る
>>> require 'vendor/autoload.php'; # composerからライブラリを読み込む
>>> use JBuilder\Common\Encoder;
=> false
>>> echo Encoder::encode(function($json) {
    $json->title = "This is a pen";
    $json->created_at = (new DateTime())->format(\DateTime::ISO8601);
    $json->updated_at = (new DateTime())->format(\DateTime::ISO8601);
    $json->author(function($json) {
      $json->name  = "Dai Akatsuka";
      $json->email = "d.akatsuka@gmail.com";
      $json->url   = "https://github.com/dakatsuka";
  });
});
{"title":"This is a pen","created_at":"2015-12-14T17:09:14+0900","updated_at":"2015-12-14T17:09:14+0900","author":{"name":"Dai Akatsuka","email":"d.akatsuka@gmail.com","url":"https:\/\/github.com\/dakatsuka"}}

以上

もし、以下の様なエラーが出た場合

Exception with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.'

php.iniに以下を追加

php.ini
date.timezone = 'Asia/Tokyo'
2
1
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
2
1