search
HomeBackend DevelopmentPHP TutorialWhat is TOML? How to configure and use TOML in PHP

本篇文章带大家聊聊PHP中的TOML配置,介绍一下在 PHP 中如何使用 TOML 配置文件格式语言,希望对大家有所帮助!

What is TOML? How to configure and use TOML in PHP

TOML 是一个配置格式化语言,特色是简洁易读。 全称为 "Tom's Obvious, Minimal Language" 其中的 Tom 为创建者 —— Tom Preston-Werner (译者注:Github CEO)。

来自其 Github  Reopo,TOML 的目的如下:

TOML 是一门简洁易用的配置信息格式化语言,高可读性来自于其优雅的语法。 TOML 为哈希表数据结构量身定制的,在各种编程语言里皆可以轻松地将 TOML 解析为各自的数据结构。

TOML 和 PHP 在一起

各种语言的 TOML 解析器可以  在其项目 WIKI 中找到

我们将利用 yosymfony/toml: 一个 PHP 的 TOML 解析器 来尝试下 TOML 语言,在你的 PHP 7.1+ 项目里使用 Composer:

composer require yosymfony/toml

TOML 的项目 Readme 里有一个示例配置信息,我们可以试着用起来:

## This is a TOML document.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # Indentation (tabs and/or spaces) is allowed but not required
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ]

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

下面是 PHP 的解析和输出:

<?php

use Yosymfony\Toml\Toml;

require __DIR__ . &#39;/vendor/autoload.php&#39;;

$data = Toml::ParseFile(__DIR__.&#39;/example.toml&#39;);

var_dump($data);

// output
php index.php
string(10) "1979-05-27"
toml-demo|⇒ php index.php
array(5) {
  ["title"]=>
  string(12) "TOML Example"
  ["owner"]=>
  array(2) {
    ["name"]=>
    string(18) "Tom Preston-Werner"
    ["dob"]=>
    object(DateTime)#243 (3) {
      ["date"]=>
      string(26) "1979-05-27 07:32:00.000000"
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "-08:00"
    }
  }
  ["database"]=>
  array(4) {
    ["server"]=>
    string(11) "192.168.1.1"
    ["ports"]=>
    array(3) {
      [0]=>
      int(8001)
      [1]=>
      int(8001)
      [2]=>
      int(8002)
    }
    ["connection_max"]=>
    int(5000)
    ["enabled"]=>
    bool(true)
  }
  ["servers"]=>
  array(2) {
    ["alpha"]=>
    array(2) {
      ["ip"]=>
      string(8) "10.0.0.1"
      ["dc"]=>
      string(6) "eqdc10"
    }
    ["beta"]=>
    array(2) {
      ["ip"]=>
      string(8) "10.0.0.2"
      ["dc"]=>
      string(6) "eqdc10"
    }
  }
  ["clients"]=>
  array(2) {
    ["data"]=>
    array(2) {
      [0]=>
      array(2) {
        [0]=>
        string(5) "gamma"
        [1]=>
        string(5) "delta"
      }
      [1]=>
      array(2) {
        [0]=>
        int(1)
        [1]=>
        int(2)
      }
    }
    ["hosts"]=>
    array(2) {
      [0]=>
      string(5) "alpha"
      [1]=>
      string(5) "omega"
    }
  }
}

配置信息示例

接下来我们试着将 Laravel 的配置信息 config/database.php 解析为 TOML ,做个对比。

需要注意的是,这只是一个示范,Laravel 的配置系统要比 TOML 高级很多,这里这样做的目的只是想在我们熟悉的配置信息里去理解 TOML:

[database]
    default = "mysql"
    migrations = "migrations"

    [database.connections.sqlite]
        driver = "sqlite"
        database = "path/to/database.sqlite"
        prefix = ""

    [database.connections.mysql]
        driver = "mysql"
        host = "127.0.0.1"
        port = "3306"
        database = "forge"
        username = "forge"
        password = ""
        unix_socket = ""
        charset = "utf8mb4"
        collation = "utf8mb4_unicode_ci"
        prefix = ""
        strict = true

    [database.redis]
        client = "predis"

        [database.redis.default]
            host = "127.0.0.1"
            password = ""
            port = 6379
            database = 0

目前来讲,TOML 并不允许 nil 和 null 值,这在一些使用 null 作为默认值的场景下会变得很不方便。

缩进是允许的,但是不强求,上面的文件使用以下写法也不会有问题:

[database]
default = "mysql"
migrations = "migrations"

[database.connections.sqlite]
driver = "sqlite"
database = "path/to/database.sqlite"
prefix = ""

# ...

构建一个 TOML 配置文件

扩展包 yosymfony/toml 除了提供解析 TOML 文件和字串外,还提供了一个 TomlBuilder 类,用来实时构建 TOML 配置信息,接下来我们还是使用 Laravel 的 config/services.php 来作为例子讲解:

<?php use Yosymfony\Toml\TomlBuilder;

require __DIR__.&#39;/vendor/autoload.php&#39;;

$builder = new TomlBuilder();

$services = $builder
    ->addComment('Third Party Services')
    ->addComment('Mailgun')
    ->addTable('services.mailgun')
        ->addValue('domain', 'mg.example.com')
        ->addValue('secret', 'mailgun-secret')
    ->addComment('Stripe')
    ->addTable('services.stripe')
        ->addValue('model', 'App\User')
        ->addValue('key', 'stripe-key')
        ->addValue('secret', 'stripe-secret')
;

file_put_contents(__DIR__.'/services.toml', $services->getTomlString());

生成的内容如下:

#Third Party Services
#Mailgun

[services.mailgun]
domain = "mg.example.com"
secret = "mailgun-secret"
#Stripe

[services.stripe]
model = "App\\User"
key = "stripe-key"
secret = "stripe-secret"

日期

TOML 支持 RFC 3339 制定的日期格式:

# Offset Date-Time
odt1 = 1979-05-27T07:32:00Z
odt2 = 1979-05-27T00:32:00-07:00
odt3 = 1979-05-27T00:32:00.999999-07:00
# space permitted per the RFC 3339 spec
odt4 = 1979-05-27 07:32:00Z

# Local Date-Time
ldt1 = 1979-05-27T07:32:00

# Local Date
ld1 = 1979-05-27

# Local Time
lt1 = 07:32:00
lt2 = 00:32:00.999999

在此篇文章编写时,上面大部分的格式都出现了错误,除了下面这一行:

dob = 1979-05-27T07:32:00-08:00

PHP 解析器会将解析成功输出为 DateTime 实例:

array(1) {
  ["dob"]=>
  object(DateTime)#128 (3) {
    ["date"]=>
    string(26) "1979-05-27 07:32:00.000000"
    ["timezone_type"]=>
    int(1)
    ["timezone"]=>
    string(6) "-08:00"
  }
}

阅读更多

前往官方项目页了解更多信息 ——  GitHub -- toml-lang/toml: Tom's Obvious, Minimal Language

项目 Wiki 里可以找到各种语言的解析器: toml-lang/toml Wiki 。

英文原文地址:https://laravel-news.com/toml-configuration-in-php

推荐学习:《PHP视频教程

The above is the detailed content of What is TOML? How to configure and use TOML in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools