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

How to get the config params in Model?

<?php
//app/config/config.php
return new \Phalcon\Config(array(
    'database' => array(
        'adapter'  => 'Mysql',
        'host'     => '127.0.0.1',
        'username' => 'root',
        'password' => 'root',
        'dbname'   => 'taobao',
        'prefix'   => 'sh_',
    ),
));
//app/config/services.php
$di->set('db', function () use ($config) {
    return new DbAdapter(array(
        'host' => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname' => $config->database->dbname,
        'prefix' => $config->database->prefix
    ));
});

How can I get the 'prefix' params in Model ?



43.9k
Accepted
answer

Do you mean the one that is store in app/config/config.php ? If so, you can register config array as a service and then can acces to its properties eveywhere in your app:


// in services.php:
$di->set('config', function() use ($config) {
return $config;
}, true);

// elsewhere in your app:
$this->config->database->dbname;


58.4k

Try this

    $this->getDI()->get('config')->database->prefix_


15.6k
<?php
//in services.php
$di->set('config', function () use ($config) {
    return $config;
}, true);

//in controller
$this->config->database->dbname;

//in model
$this->getDI()->get('config')->database->prefix

Thank your!!! Both need!!!

In services: Phalcon 3.0.1

$di->set('myservice', function () {
    $config = $this->getConfig();
    //...code...
}, true);