たなちの備忘録

自分の知識をストックしていくためのブログ

【CakePHP3】はじめたときにわからなかった箇所の細かいメモ

スポンサーリンク

過去の記事をはてな記法に変更した。
参考になるドキュメントの備忘録も兼ねる。

その他忘備録

_serializeとは?

データビューを使用する際に他のビュー変数をシリアル化する必要があることを示すビュー変数。Cookbookでは1/14時点で日本語版がなかった。
シリアル化とは、扱うデータをそのまま保存したり、送受信できるようにすること。DBにarray型の値をarray型のまま保存するときなどに使う。解説はこちらのサイトがわかりやすい。覚えておきたい「シリアライズ serialize」 | hijiriworld Web

<?php
namespace App\Controller;

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

    public function index()
    {
        // Set the view vars that have to be serialized.
        $this->set('articles', $this->paginate());
        // Specify which view vars JsonView should serialize.
        $this->set('_serialize', ['articles']);
    }
}

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view. This lets you skip defining template files for your controller actions if you don’t need to do any custom formatting before your data is converted into json/xml.

_serializeキーは、データビューを使用するときに他のビュー変数をシリアル化する必要があることを示す特殊なビュー変数です。 これにより、データがjson / xmlに変換される前にカスタムフォーマットを行う必要がない場合、コントローラアクション用のテンプレートファイルの定義を省略できます。

If you need to do any formatting or manipulation of your view variables before generating the response, you should use template files. The value of _serialize can be either a string or an array of view variables to serialize:

レスポンスを生成する前にビュー変数の書式設定や操作を行う必要がある場合は、テンプレートファイルを使用する必要があります。 _serializeの値は、直列化する文字列またはビュー変数の配列のいずれかです。

JSON and XML views - 3.5

Number->format()とは?

Cookbookの記事:Number - 3.5

数値を整形し、オプションがない場合のデフォルトは小数点以下が表示されなくなる。

<?php
$this->Number->format($value, $options);