Table of Contents
TOML 和 PHP 在一起
配置信息示例
构建一个 TOML 配置文件
日期
阅读更多
Home Backend Development PHP Tutorial What is TOML? How to configure and use TOML in PHP

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

Sep 21, 2022 am 10:05 AM
php toml

本篇文章带大家聊聊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
Copy after login

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"
]
Copy after login

下面是 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"
    }
  }
}
Copy after login

配置信息示例

接下来我们试着将 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
Copy after login

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

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

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

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

# ...
Copy after login

构建一个 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(&#39;Third Party Services&#39;)
    ->addComment(&#39;Mailgun&#39;)
    ->addTable(&#39;services.mailgun&#39;)
        ->addValue(&#39;domain&#39;, &#39;mg.example.com&#39;)
        ->addValue(&#39;secret&#39;, &#39;mailgun-secret&#39;)
    ->addComment(&#39;Stripe&#39;)
    ->addTable(&#39;services.stripe&#39;)
        ->addValue(&#39;model&#39;, &#39;App\User&#39;)
        ->addValue(&#39;key&#39;, &#39;stripe-key&#39;)
        ->addValue(&#39;secret&#39;, &#39;stripe-secret&#39;)
;

file_put_contents(__DIR__.&#39;/services.toml&#39;, $services->getTomlString());
Copy after login

生成的内容如下:

#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"
Copy after login

日期

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
Copy after login

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

dob = 1979-05-27T07:32:00-08:00
Copy after login

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"
  }
}
Copy after login

阅读更多

前往官方项目页了解更多信息 ——  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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles