Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Access to the configuration when adding a Mysql connection in the FactoryDefault

Hi,

I have an ini file:

[database]
host      = localhost
username  = test
password  = ****
dbname    = test

In index.php i have:

use Phalcon\Config\Adapter\Ini as IniConfig;
$di = new FactoryDefault();
$di->set('config', function () {
return new IniConfig("config/config.ini");
});
// Set up the database service
$di->set('db', function () {
return new PdoMysql(
    array(
        "host"     => $this->config->database->host, // or $di->config->database->host,
        "username" => $this->config->database->userName,
        "password" => $this->config->database->password,
        "dbname"   => $this->config->database->dbName
    )
);
});

When I try to open the connexion it doesnt work, i have an error on all " $this->config->database->....":

<b>Notice</b>:  Undefined property: Phalcon\Di\FactoryDefault::$config

Can you help me?



7.1k
Accepted
answer

Which version of Phalcon are you using? For 2.0.x you should write

use Phalcon\Config\Adapter\Ini as IniConfig;

$di = new FactoryDefault();

// Set up config service
$di->set('config', function () {
    return new IniConfig(... path ...);
}, true);

// Set up the database service
$di->set('db', function () use ($di) {
    $config = $di->get('config');
    return new PdoMysql([
        "host"     => $config->database->host,
        "username" => $config->database->userName,
        "password" => $config->database->password,
        "dbname"   => $config->database->dbName
    ]);
}, true);

Thank you, it works! :)

Your code with $this should work for 2.1.0(currently RC version)