Installation:
composer require wp-cli/mustangostang-spyc
Add to composer.json if not using global Composer.
First Use Case: Load a YAML file into a PHP array:
use Spyc;
$data = Spyc::YAMLLoad('path/to/file.yaml');
Or dump an array to YAML:
$yamlString = Spyc::YAMLDump(['key' => 'value']);
Where to Look First:
config_path() or storage_path() for file operations.Configuration Loading: Load YAML configs in a service provider:
public function boot()
{
$config = Spyc::YAMLLoad(config_path('custom.yaml'));
config(['custom.settings' => $config]);
}
Dynamic YAML Generation: Serialize Laravel collections/models to YAML:
$users = User::all()->toArray();
$yaml = Spyc::YAMLDump($users);
Storage::disk('logs')->put('users.yaml', $yaml);
CLI Tools: Use in Artisan commands for data export:
class ExportCommand extends Command
{
public function handle()
{
$data = Spyc::YAMLLoad('input.yaml');
$this->info(Spyc::YAMLDump($data, 10)); // Pretty-print
}
}
Validation:
Combine with Laravel’s Validator:
$data = Spyc::YAMLLoad('input.yaml');
$validator = Validator::make($data, [
'name' => 'required|string',
'email' => 'required|email',
]);
Legacy Migration: Convert old YAML configs to PHP arrays for Laravel’s native config:
$legacyConfig = Spyc::YAMLLoad('legacy/config.yaml');
config(['legacy' => $legacyConfig]);
YAML 1.0 Only:
symfony/yaml if unsure.# This will break:
defaults: &defaults
adapter: mysql
host: localhost
No Error Handling:
Spyc_Exception. Wrap calls:
try {
$data = Spyc::YAMLLoad('file.yaml');
} catch (Spyc_Exception $e) {
Log::error("YAML parse error: " . $e->getMessage());
}
Performance:
symfony/yaml for large files. Benchmark if parsing >1MB YAML.No Laravel Facades:
file_get_contents()). Avoid for sensitive paths.Deprecation Risk:
symfony/yaml.Pretty-Printing:
Use Spyc::YAMLDump($data, 10) for human-readable output (indent level = 10).
String Parsing: Parse YAML strings directly:
$data = Spyc::YAMLLoadString($yamlString);
Laravel Service Binding (Optional): Bind to container for DI:
$this->app->singleton('spyc', function () {
return new \Spyc();
});
Testing:
Validate against symfony/yaml for critical data:
$symfonyData = Symfony\Component\Yaml\Yaml::parseFile('file.yaml');
$spycData = Spyc::YAMLLoad('file.yaml');
$this->assertEquals($symfonyData, $spycData);
Alternatives:
spatie/laravel-yaml for Laravel-specific features.symfony/yaml if YAML 1.2 or performance is needed.How can I help you explore Laravel packages today?