Kohana's config files look like this.. here is an example of a database config file (simplified)
return array(
'dbhost' => 开发者_如何学JAVA'localhost',
'user' => 'Tom_Jones'
);
I've also got a CMS which wants the connection details. Whilst the CMS uses a different user (with more rights), I'd like to know the best way to include this file and get the data out of it (so as to not repeat myself for hostname and dbname).
I haven't thought up of any elegant solutions yet and have not yet dug around Kohana to see how it does it. It's late Friday here so it's probably really obvious to everyone except me.
Update
My apologies, I forgot to include that this is using Kohana 3!
In Kohana v3, in the Kohana_Config_Reader
class, method load()
:
$config = Arr::merge($config, require $file);
require $file
is used to load the array in the configuration file.
I downloaded Kohana and could not files that look like your example, but if you are using the current version you could repurpose the config files like this:
<?php
// Your script
define('SYSPATH', 'true'); // So Kohana doesn't kill our script
$config = array();
include('path/to/system/config/database.php');
echo $config['default']['connection']['user']; // Echos database user
?>
http://docs.php.net/function.include says:
Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function.
Let's take your example code
<?php // test2.php
return array(
'dbhost' => 'localhost',
'user' => 'Tom_Jones'
);
and a script that includes test2.php
<?php
$cfg = include 'test2.php';
if ( !is_array($cfg) ) {
// ... add useful error handling here ...
}
// you might want to test the structure of $cfg
// before accessing specific elements
echo $cfg['dbhost'];
prints localhost
.
The documentation contains some basic info on how you access those config files. So if you have the following in a file called db.php
in application/config
:
<?php defined('SYSPATH') or die('No direct script access.');
return array(
'host' => 'localhost',
'user' => 'Tom_Jones'
);
You'd access them like this:
$options = Kohana::config('db');
echo $options['user'];
echo $options['host'];
Or like this:
echo Kohana::config('db.user');
echo Kohana::config('db.host');
Or like this:
echo Kohana::config('db')->user;
echo Kohana::config('db')->host;
精彩评论