LoginSignup
0
1

More than 3 years have passed since last update.

【PHP8】Docker で PECL の YAML 関数(YAML パーサー)をインストールして使う

Last updated at Posted at 2020-08-28

PHP の YAML 関数は標準で PHP にバンドルされていません。

YAML 関数で、YAML データを PHP 配列にパース(構文解析して変換)、もしくは PHP 配列から YAML データにパースするには PECL の拡張ジュールをインストールする必要があります

しかし、最新(2020/08/28 現在)の php:8.0.0beta2 および php:8.0.0beta2-alpine イメージには PECL はインストールされていません。PHP 7.4 以降から PEAR/PECL インストーラーは排除されたようです。

TL; DR

PECL をソースからビルドする必要があるのですが、それも面倒なので pecl コマンド入りのイメージを作成しました。Intel/AMD だけでなくラズパイなどの ARMv5,v7, ARM64 でも動作します。

docker pull keinos/php8-jit:latest
$ docker run --rm keinos/php8-jit pecl version
PEAR Version: 1.10.12
PHP Version: 8.0.0-dev
Zend Engine Version: 4.0.0-dev
Running on: Linux 3fc54c34122a 4.19.76-linuxkit #1 SMP Tue May 26 11:42:35 UTC 2020 x86_64

また、PECL リポジトリのビルド済みパッケージで動かないものが多いので、PECL パッケージもソースからインストールできるようにしています。

要yaml-dev
docker-php-ext-pecl install yaml

TS; DR

Dockerfile
FROM keinos/php8-jit:latest

USER root

COPY sample.php /app/sample.php

RUN \
    apk --no-cache add yaml-dev && \
    docker-php-ext-pecl install yaml

ENTRYPOINT [ "php", "/app/sample.php" ]
sample.php
<?php

// YAML のサンプル文字列
$yaml = <<<EOD
---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to: *id001
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

// YAML 文字列を PHP 配列にパース
$parsed = yaml_parse($yaml);

// 比較テスト
$actual = json_encode($parsed);
$expect = '{"invoice":34843,"date":"2001-01-23","bill-to":{"given":"Chris","family":"Dumars","address":{"lines":"458 Walkman Dr.\n        Suite #292","city":"Royal Oak","state":"MI","postal":48046}},"ship-to":{"given":"Chris","family":"Dumars","address":{"lines":"458 Walkman Dr.\n        Suite #292","city":"Royal Oak","state":"MI","postal":48046}},"product":[{"sku":"BL394D","quantity":4,"description":"Basketball","price":450},{"sku":"BL4438H","quantity":1,"description":"Super Hoop","price":2392}],"tax":251.42,"total":4443.52,"comments":"Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."}';

echo '- Function test ... ', ($expect === $actual) ? 'OK' : 'NG', PHP_EOL;

参考文献

0
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
0
1