Installation:
composer require dubiy/yamlok
Add the service provider to config/app.php under providers:
Dubiy\Yamlok\YamlokServiceProvider::class,
Publish Config (if needed):
php artisan vendor:publish --provider="Dubiy\Yamlok\YamlokServiceProvider"
This creates config/yamlok.php. Update the file key to point to your YAML file (e.g., app/config/settings.yml).
First Use Case: Load and dump a YAML file:
use Dubiy\Yamlok\Facades\Yamlok;
$data = Yamlok::read(); // Loads YAML as associative array
Yamlok::write($data); // Overwrites YAML file with array
Reading YAML:
// Load YAML into an array
$config = Yamlok::read('path/to/custom.yml'); // Optional: Override config path
// Merge with existing config (if using facade)
$merged = array_merge(Yamlok::getConfig(), $customData);
Writing YAML:
// Update and save
$updatedData = Yamlok::getConfig(); // Get current config
$updatedData['new_key'] = 'value';
Yamlok::write($updatedData);
// Write to a custom file
Yamlok::write($data, 'path/to/output.yml');
Dynamic Configuration: Use the facade in controllers/services to fetch/update settings:
// In a service
public function __construct() {
$this->settings = Yamlok::getConfig();
}
Environment-Specific Files: Override the config path dynamically:
$env = env('APP_ENV');
$file = "config/settings.{$env}.yml";
$data = Yamlok::read($file);
if (!is_array($data)) {
throw new \InvalidArgumentException('Data must be an array.');
}
Yamlok::extend(function ($yamlok) {
$yamlok->onRead(function ($data) {
// Pre-process data
});
});
Caching:
Yamlok::setCache(false);
php artisan yamlok:clear-cache
(Note: This command is not documented in the README but inferred from the TODO list.)File Permissions:
chmod 664 app/config/settings.yml
YAML Syntax Errors:
Symfony/Yaml for pre-checks:
use Symfony\Component\Yaml\Yaml as SymfonyYaml;
try {
SymfonyYaml::parseFile($file);
} catch (\Exception $e) {
// Handle error
}
Global Config Overrides:
dubiy_yamlok.file config is not documented as dynamic. To change it at runtime:
Yamlok::setConfigPath('new/path.yml');
Yamlok::extend(function ($yamlok) {
$yamlok->onRead(function ($data) {
\Log::debug('YAML loaded:', ['data' => $data]);
});
});
Yamlok::read() (not Yamlok::load() or similar).Custom Parsers: Override the default parser (Symfony Yaml) by binding a new parser to the container:
$this->app->bind('yaml.parser', function () {
return new \Custom\Yaml\Parser();
});
Pre/Post Hooks:
Use the extend() method to add logic before/after operations:
Yamlok::extend(function ($yamlok) {
$yamlok->onWrite(function ($data, $file) {
// Encrypt sensitive data
$data['secret'] = encrypt($data['secret']);
});
});
TODO: Cache Removal:
// Example: Add a cache timestamp to the config
$cacheFile = storage_path('yamlok_cache.json');
if (file_exists($cacheFile) && filemtime($cacheFile) > now()->subHours(1)->timestamp) {
// Use cached data
} else {
// Re-parse YAML
}
How can I help you explore Laravel packages today?