symfony/yaml
Symfony Yaml component for parsing and dumping YAML. Load YAML files or strings into PHP arrays and objects, and generate clean YAML output with configurable dumping options. Well-tested, documented, and maintained as part of the Symfony ecosystem.
Installation:
composer require symfony/yaml
Laravel’s Composer autoloader will handle the rest.
First Use Case: Parse a YAML file into a PHP array:
use Symfony\Component\Yaml\Yaml;
$yaml = Yaml::parseFile(__DIR__.'/config.yaml');
// $yaml is now a PHP array
Dump a PHP array back to YAML:
$yamlString = Yaml::dump($phpArray, 10, 2); // Indent: 10, inline: 2
file_put_contents(__DIR__.'/output.yaml', $yamlString);
Where to Look First:
Yaml::parse(), Yaml::parseFile(), Yaml::dump(), and Yaml::dumpFile() methods in the source code.Load Laravel’s config/ YAML files dynamically (e.g., for multi-environment overrides):
$envConfig = Yaml::parseFile(config_path("environments/{$env}.yaml"));
config()->set($envConfig); // Merge into Laravel's config
Parse Kubernetes manifests or Helm values:
$manifest = Yaml::parseFile(storage_path('k8s/deployment.yaml'));
$container = $manifest['spec']['template']['spec']['containers'][0];
Load YAML-defined validation rules at runtime:
$rules = Yaml::parseFile(config_path('validation/rules.yaml'));
Validator::extend($rules['custom']['regex']);
Cache parsed YAML to avoid repeated I/O:
$cacheKey = 'yaml_config_' . md5($filePath);
$yaml = Cache::remember($cacheKey, now()->addHours(1), function () use ($filePath) {
return Yaml::parseFile($filePath);
});
Generate YAML for APIs, logs, or external systems:
$logEntry = [
'timestamp' => now()->toIso8601String(),
'level' => 'error',
'message' => 'Database connection failed',
'context' => ['query' => 'SELECT * FROM users']
];
Yaml::dumpFile(storage_path('logs/error.yaml'), [$logEntry], 10, 2);
Combine with Respect/Validation or Laravel’s Validator:
$yamlData = Yaml::parseFile($file);
$validator = Validator::make($yamlData, [
'database.host' => 'required|string',
'database.port' => 'required|integer|between:1,65535',
]);
Override default configs with environment-specific YAML:
$defaults = Yaml::parseFile(config_path('default.yaml'));
$overrides = Yaml::parseFile(config_path("environments/{$env}.yaml"));
$config = array_merge_recursive($defaults, $overrides);
Use Symfony\Component\Yaml\Inline for inline YAML in PHP strings:
$inlineYaml = <<<YAML
services:
- { name: "app", class: "App\\Services\\AppService" }
YAML;
$services = Yaml::parse($inlineYaml);
Catch parsing errors gracefully:
try {
$data = Yaml::parse($yamlString);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
Log::error("Invalid YAML: " . $e->getMessage());
throw new \RuntimeException("Configuration error", 0, $e);
}
Service Provider Binding:
$this->app->singleton('yaml', function () {
return new Yaml();
});
Then inject via constructor:
public function __construct(private Yaml $yaml) {}
Artisan Commands: Use YAML for CLI config:
$config = Yaml::parseFile(base_path('artisan-config.yaml'));
$this->option('timeout', $config['default_timeout']);
Laravel Mix/Webpack: Parse YAML for asset configurations:
$mixConfig = Yaml::parseFile(base_path('webpack.mix.yaml'));
mix()->setPublicPath($mixConfig['public_path']);
Stream Large Files:
For files >10MB, use SplFileObject with a custom parser (Symfony/YAML loads entire file into memory).
Example:
$file = new SplFileObject(__DIR__.'/large.yaml');
$parser = new \Symfony\Component\Yaml\Parser();
$data = $parser->parse($file); // Still loads all, but demonstrates API
Cache Parsed YAML:
Use Laravel’s cache or Symfony\Component\Cache:
$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
$yaml = $cache->get($filePath, function () use ($filePath) {
return Yaml::parseFile($filePath);
});
Unit Test Parsing:
public function testYamlParsing()
{
$yaml = <<<YAML
name: "John Doe"
age: 30
YAML;
$expected = ['name' => 'John Doe', 'age' => 30];
$this->assertEquals($expected, Yaml::parse($yaml));
}
Mock YAML Files:
Use Yaml::parse() with hardcoded strings in tests:
$this->app->instance('yaml', fn() => Yaml::parse($mockYaml));
Duplicate Keys in YAML:
Yaml::parse($yaml, Yaml::PARSE_CONSTANT) to keep the last value.# Invalid YAML (duplicate key)
key: value1
key: value2
Fix: Merge keys manually or restructure YAML.Unquoted Multiline Scalars:
unquoted: |
line 1
line 2
line 3 # comment
"...") or ensure no blank lines between content.Flow Style vs. Block Style:
{key: value}) may not render as expected in nested structures.Yaml::DUMP_OBJECT_AS_ARRAY flag for consistent output:
Yaml::dump($array, null, 10, Yaml::DUMP_OBJECT_AS_ARRAY);
Null Handling:
null values are dumped as null. Use Yaml::DUMP_NULL_AS_EMPTY to output empty strings:
Yaml::dump($array, null, 10, Yaml::DUMP_NULL_AS_EMPTY);
PHP 8.4+ Requirements for v8.x:
composer require symfony/yaml:^7.4
Memory Limits:
memory_limit. Use streaming libraries like spatie/yaml-front-matter for edge cases.try {
Yaml::parse($yaml);
} catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
echo "Error at line {$e->getLine()}: {$e->getMessage()}\n";
}
2
How can I help you explore Laravel packages today?