CakeFest 2024: The Official CakePHP Conference

MessageFormatter クラス

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

はじめに

MessageFormatter は、言語に依存しない連結されたメッセージを作成するための具象クラスです。 このクラスのメソッドを使用して、 エンドユーザー向けのすべてのメッセージを作成します。

MessageFormatter クラスは、プログラムから渡したさまざまな部品 (テキスト、数値、日付など) を組み合わせてメッセージを作成します。 MessageFormatter クラスでは、 プログラム側が部品の順序を気にする必要はありません。 このクラスでは、各部品に対して書式指定を使用し、 リソースバンドル内のひとつの文字列にメッセージをまとめます。 たとえば、 "Finished printing x out of y files..." のようなメッセージがあった場合に MessageFormatter は各翻訳に対して柔軟な表示を行います。

これまでは、エンドユーザー向けのメッセージは文章として作成し、 文字列で処理していました。 これは地域化の際にさまざまな問題を引き起こしていました。 文章の構造や単語の並び順、そして数値の書式などは 各言語によってさまざまに異なっているからです。 言語に依存しない方法でメッセージを作成するには、 メッセージの各部分を分割し、そこにデータへのキーを指定するようにします。 このキーを使用して、MessageFormatter クラスはメッセージの各部分を連結します。 そして地域化して適切な書式にした文字列をエンドユーザー向けに表示します。

MessageFormatter はオブジェクトのセットを受け取ってそれをフォーマットし、 フォーマットした文字列を適切な位置に埋め込みます。 MessageFormatter のフォーマットを選択することで、 数値にあわせて複数形を選択することができます。 一般的には、メッセージのフォーマットはリソースから取得し、 引数は実行時に動的に与えるようになります。

クラス概要

class MessageFormatter {
/* メソッド */
public __construct(string $locale, string $pattern)
public static create(string $locale, string $pattern): ?MessageFormatter
public static formatMessage(string $locale, string $pattern, array $values): string|false
public format(array $values): string|false
public getErrorCode(): int
public getLocale(): string
public static parseMessage(string $locale, string $pattern, string $message): array|false
public parse(string $string): array|false
public setPattern(string $pattern): bool
}

目次

add a note

User Contributed Notes 1 note

up
3
from dot php dot net at NOSPAM dot brainbox dot cz
9 years ago
MessageFormatter does not work with DateTime instances as parameters in PHP < 5.5. Instance will be converted to timestamp with value 0 (e.g. 1970-01-01) and following Notice will be raised: „Object of class DateTime could not be converted to int“. You have to manually convert the instance to timestamp in these old PHP versions.

<?php
$datetime
= new DateTime();
if (
PHP_VERSION_ID < 50500) { // PHP < 5.5 needs conversion to timestamp
MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime->getTimestamp()));
} else {
// current code
MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime));
}
?>
To Top