We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Services in YAML

Hi, For now i define all services using DI in PHP code, i'm wondering if its possible to define services and all dependencies in YAML file, is it possible using phalcon v1.2.6 ?

I think currently it is only possible to load config files from native arrays and ini files. You would have to implement an own yaml file adapter. I'm not a friend of yaml files because it costs performance to parse yaml or other config files.

thanks for the response, as its cost performance, i'll stick with native PHP.



98.9k
edited Mar '14

You can use the PECL YAML extension: https://mx1.php.net/yaml together with the following custom adapter:

<?php

use Phalcon\Config;
use Phalcon\Config\Exception;

/**
 * YamlConfig
 * Reads yaml files and convert it to Phalcon\Config objects.
 */
class YamlConfig extends Config implements \ArrayAccess
{

    /**
     * Class constructor.
     *
     * @param  string                    $filePath
     * @param  array                     $callbacks
     * @throws \Phalcon\Config\Exception
     */
    public function __construct($filePath, $callbacks = array())
    {
        if (!extension_loaded('yaml')) {
            throw new Exception('Yaml extension not loaded');
        }

        $mustBeRead = false;
        $cachedPath = dirname($filePath) . DIRECTORY_SEPARATOR . '_' . str_replace(DIRECTORY_SEPARATOR, '_', $filePath) . '.php';
        if (!file_exists($cachedPath)) {
            $mustBeRead = true;
        } else {
            if (filemtime($filePath) > filemtime($cachedPath)) {
                $mustBeRead = true;
            }
        }

        if ($mustBeRead) {
            $ndocs = 0;
            if (false === $result = yaml_parse_file($filePath, 0, $ndocs, $callbacks)) {
                throw new Exception('Configuration file ' . $filePath . ' can\'t be loaded');
            }
            file_put_contents($cachedPath, '<?php return ' . var_export($result, true) . ';');
        } else {
            $result = require $cachedPath;
        }

        parent::__construct($result);
    }
}

Usage:

$config = new YamlConfig("config.yml");

This adapter caches the PHP representation of the YAML version reducing the overhead of parsing it every time. If the original Yaml is modified it regenerates the PHP version.

Adapter in incubator rely on yaml php extension.