Introduction to TOML Configuration in PHP

Last updated on by

Introduction to TOML Configuration in PHP image

TOML is a configuration file format language that is intended to be minimal and easy to read. TOML stands for “Tom’s Obvious, Minimal Language,” which refers to the creator Tom Preston-Werner.

I first encountered using Confd, a configuration management tool by Kelsey Hightower, and as advertised I didn’t even realize I was using TOML at first or anything about TOML and I was able to make sense of it immediately.

From the GitHub repo, the goal of TOML is as follows:

TOML aims to be a minimal configuration file format that’s easy to read due to obvious semantics. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages.

TOML and PHP Sitting in a Tree

I thought I’d experiment with ways I could use TOML with PHP as a simple, yet powerful configuration format. You can find a list of parsers that work with the TOML specification on the project’s wiki, which includes three PHP implementations at the time of writing.

To use TOML with PHP check out yosymfony/toml: A PHP parser for TOML and install it in your PHP 7.1+ projects with composer:

composer require yosymfony/toml

Check the linked wiki for other implementations (including a PHP extension)

I decided the first thing I’d try is take the example TOML configuration from the official readme and see the PHP array output. First, this is the example TOML configuration file:

<br></br>## 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"
]

And here’s the PHP output after parsing the file:

<?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"
}
}
}

Configuration Examples

I thought it would be fun to convert Laravel’s config/database.php file (partially) to TOML just to give you an idea of the equivalent data structure in a PHP configuration file vs. TOML.

Again, this serves as an example, and Laravel’s configuration system is far more advanced. I thought it would be helpful to understand how to use TOML by comparing it to something familiar to most of our readers:

[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

The TOML specification doesn’t allow nil or null values as far as I can tell from various GitHub issues and the consensus seems to be to omit a key if it’s null. This seems somewhat counter-intuitive in some ways to me if you intend to convey that a key exists, but the default value being null.

Indentation is legal, but not required so the above file could also look like this:

[database]
default = "mysql"
migrations = "migrations"
 
[database.connections.sqlite]
driver = "sqlite"
database = "path/to/database.sqlite"
prefix = ""
 
# ...

Building a TOML Configuration File

Besides parsing TOML strings and files, the yosymfony/toml package includes a TomlBuilder class. I thought I’d create a TOML file the represents Laravel’s config/services.php config file to test out the builder:

<?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());

The builder example generates the following TOML file:

#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"

The apparent disadvantage of TOML over PHP configuration files is the missing environment variable functionality, but it’s cool to see how powerful the TOML configuration format can be for both ingesting and exporting configuration from your code.

Dates

TOML supports RFC 3339 dates in a few varieties including Offset Date-Time, Local Date-Time, Local Date, and Local Time:

# 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

At the time of writing, many of these formats failed in the PHP parser I tried, but this format works:

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

The cool part about the PHP parser implementation is converting these dates to DateTime instances:

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"
}
}

Learn More

To learn more about the TOML language check out the GitHub – toml-lang/toml: Tom’s Obvious, Minimal Language readme and also the toml-lang/toml Wiki for projects using TOML as well as a full list of parsers.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Basset is an alternative way to load CSS & JS assets image

Basset is an alternative way to load CSS & JS assets

Read article