本篇文章带大家聊聊PHP中的TOML配置,介绍一下在 PHP 中如何使用 TOML 配置文件格式语言,希望对大家有所帮助!
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__ . '/vendor/autoload.php'; $data = Toml::ParseFile(__DIR__.'/example.toml'); 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__.'/vendor/autoload.php'; $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!

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

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.

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

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

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor
