How to use a YAML config file in Silex Framework

不羁岁月 提交于 2019-12-02 17:37:54

First of all, add the Symfony Yaml component to your composer.json

"symfony/yaml": "2.1.*@dev",

Use the right version choosing directly from the packagist page: https://packagist.org/packages/symfony/yaml

Now, you can add the deralex YamlConfigProvider, a simple and useful Silex provider. Add it to your composer.json:

"deralex/yaml-config-service-provider": "1.0.x-dev"

Here the official github page: https://github.com/deralex/YamlConfigServiceProvider

Here the packagist page: https://packagist.org/packages/deralex/yaml-config-service-provider

UPDATE

Install the dependencies with ./composer.phar update command and finally add these lines to your app file:

$app = new Silex\Application();
$app->register(new DerAlex\Silex\YamlConfigServiceProvider(__DIR__ . '/settings.yml'));

Now, for example, you can do this:

settings.yml

database:
    driver: pdo_mysql
    host: localhost
    dbname: database_name
    user: root
    password: password
    charset: utf8

index.php

$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => $app['config']['database']
));

This package in the answer does not work for Silex 2.0 that is why I've created package that works for Silex 2.0 and Symfony/Yaml 3.1. Maybe someone looking for this answer will find it useful

https://packagist.org/packages/rpodwika/yaml-config-service-provider

to use run command

composer require rpodwika/yaml-config-service-provider

or add

"rpodwika/yaml-config-service-provider" : "dev-master" 

to your composer.json

github link https://github.com/rpodwika/yaml-config-service-provider

to use:

<?php

require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->register(new Rpodwika\Silex\YamlConfigServiceProvider("settings.yml"));

echo $app['config']['database']['driver'];

The LoadConfigExtension described by @fbrandel (above in comments) allows you to share the yml loader config service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!