简体   繁体   中英

CakePHP: Accessing database.php values

I need to retrieve values from CakePHP's config file database.php from one of my controllers.

I'm maintaining an ex-employee's code, so I'm not positive how much of this adheres to default structures. I'm hoping this is fairly straightforward, but I can't seem to Google the right info.

File: app/config/database.php

class DATABASE_CONFIG
{
    var $db1 =
        array('driver' => 'mysqli',
              'connect' => 'mysql_connect',
              'host' => 'localhost',
              'login' => 'username',
              'password' => 'password',
              'database' => 'schema',
              'prefix' => '');
}

File: app/controllers/my_controller.php

// here is where I need to retrieve
// the database login and password values

What syntax can I use here? Is it even possible to retrieve these values, or are they only accessible to the guts of the CakePHP framework?

$fields = get_class_vars('DATABASE_CONFIG')

echo $fields['db1']['login'];

Well, I have to say the above answer is a much quicker and simpler method than what I've been using, but just for argument's sake:

    App::Import('ConnectionManager');
    $ds = ConnectionManager::getDataSource('default');
    $dsc = $ds->config;

    echo $dsc['host'];
    echo $dsc['login'];
    echo $dsc['password'];
    echo $dsc['database'];

I guess if anything this protects your code from a change in the name of the 'DATABASE_CONFIG' class.

I know this is an old post but I just found out that there is a way to list all items in the DATABASE_CONFIG class without using get_class_vars() function.

I think get_class_vars() only works on public classes anyways.

http://api.cakephp.org/2.4/class-ConnectionManager.html#_enumConnectionObjects

App::uses('ConnectionManager', 'Model');
$dataSource = ConnectionManager::enumConnectionObjects();

Should list everything, in fact it's output is identical to @RaYell answer.

$ds = ConnectionManager::getDataSource('default')->config;
echo $ds['login'];

But from the CakePHP 2.1 and above the given solution won't work since there are some big changes from Cake version 2.x. For Cake 2.1 and above the following way should work as I tested.

App::uses('ConnectionManager', 'Model');
$ds = ConnectionManager::getDataSource('default');
$user = $ds->config['login'];

There other options you may found in the following link:

How Can I Read the DB Configuration Settings From a Cake Shell?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM