axy/docker-compose-config

与docker-compose配置一起工作

0.2.0 2023-03-16 12:14 UTC

This package is auto-updated.

Last update: 2024-09-19 13:48:45 UTC


README

Latest Stable Version Minimum PHP Version Tests Coverage Status License

docker-compose配置一起工作。

此库不会创建和加载任何文件,也不会解析和构建Yml。使用常规PHP数组作为输入和输出。

ComposeConfig

ComposeConfig 是库的主要类。您可以选择创建一个空的配置或加载现有的。

use axy\docker\compose\config\ComposeConfig;

// data loading is a matter of external code
$data = Yaml::parse(file_get_contents('docker-compose.yml'));
$config = new ComposeConfig($data);

// manipulation
$service = $config->services->create('php');
$service->build->context = './build';
// ...

// data saving is a matter of external code
$data = $config->getData();
$yaml = Yaml::dump($data, 5);
file_put_contents('docker-compose.yml', $yaml);

没有参数的构造函数 new ComposeConfig() 创建一个空的配置。

验证

库在加载时不会进行严格的验证。如果字段格式错误,它将被转换为正确值或忽略。

结构

配置组件的类有其自己的一组属性,对应于该组件的字段。例如,ComposeConfig 有属性 $version$services$volumes$network

对于简单字段创建简单属性。可空字符串(如 $version)或数组。复杂字段对应于特定类的对象。例如,$config->services 是服务对象的容器。

所有结构在加载时都会初始化,即使它们在源文件中没有指定。例如,即使没有指定此服务的 build 部分,您也可以像处理对象一样处理 $service->build。只是 $service->build 的所有字段都将为空,并且除非您更改它,否则此字段不会被放入结果中。

通常,带有 NULL、空字符串或空值的字段不会被放入结果中。对象本身决定这个问题。

additional

一些类有公共数组 additional。所有不对应于其他属性的字段都会落入其中。

version: "3.8"

services:
    www:
        image: nginx

foo: bar
bar: foo

versionservices 是标准字段,但 foobar 将添加到 additional。所有附加字段都将按原样添加到结果中。

TDisable

Trait TDisable 定义以下方法

  • isEnabled(): bool
  • disable(): void
  • enable(): void

具有此 trait 的对象可以被禁用

$config->services['db']->disable(); // disable service "db"

已禁用的组件将从结果配置中删除。已禁用的对象将存储其所有数据,并在 enable() 后恢复。

$config->services

服务列表。实现 ArrayAccess

$php = $config->services->create('php'); // create empty service php
$www = $config->services->create('www', ['image' => 'nginx']); // create service based on loaded config
$config->services['php']->build->context = './build'; // get service by name
$config->services->disableService('db'); // disable services if it exists
$config->services->clear(); // clear the service list

服务对象

ComposeService 实例包含以下属性

  • ?string $image
  • ?string $container_name
  • ?string $restart
  • BuildSection $build
  • PortsSection $ports
  • ExposeSection $expose
  • EnvironmentSection $environment
  • LabelsSection $labels
  • ?string $network_mode
  • ServiceNetworksSection $networks
  • DependsOnSection $depends_on
  • array $additional

一些部分,如 portsexpose 和(服务内部的)volumes,只是一个无名的值列表。有三个用于搜索的方法,如 $volumes->findBySource()。也可以使用 "keys" 和 "groups"。

您可以将值与键(任意字符串)绑定或将它添加到组中。键和组在 yml 文件中不会表示,但可用于配置操作。

// Base template
$service->volumes->add('./app:/var/www/app'); // bind volume without key
$service->volumes->add('./log:/var/log/nginx', 'nginx_log'); // with key "nginx_log"

// ...

// I want disable mount nginx log
$service->volumes->getByKey('nginx_log')->disable();