我有一个数据库类,我想在其中传递配置。我必须保持"框架"和应用程序文件分开。 这是我的配置类
<?php namespace Fzaffa\System;
class Config {
private $items = [];
public function get($name)
{
list($file, $key) = $this->parseName($name);
$this->includeIfNotCached($file);
$item = $this->parseItemToReturn($key, $file);
return $item;
}
/**
* @param $file
*/
private function includeIfNotCached($file)
{
if ( ! array_key_exists($file, $this->items))
{
$arr = include __DIR__ . '/App/Config/' . $file . '.php';
$this->items[$file] = $arr;
}
}
/**
* @param $name
* @return array
*/
private function parseName($name)
{
if (strpos($name, '.'))
{
list($file, $key) = explode('.', $name);
return [$file, $key];
}
return [$name, null];
}
/**
* @param $key
* @param $file
* @return mixed
*/
private function parseItemToReturn($key, $file)
{
if ($key)
{
return $this->items[$file][$key];
}
else
{
return $this->items[$file];
}
}
}
这是我的数据库类
<?php namespace Fzaffa\System;
use PDO;
class Database {
private $host = 'localhost';
private $dbname = 'mycms';
private $user = 'homestead';
private $pass = 'secret';
private $dbh;
private $error;
private $statement;
public function __construct()
{
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ";charset=utf8";
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try
{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e)
{
$this->error = $e->getMessage();
}
}
我希望能够在index.php中实例化配置对象(所有引导和路由都在这里发生),就像这样 $ config = new \ Fzaffa \ system \ Config; 然后在$ class-&gt; get(&#39; database.username&#39;)等类中使用配置变量
特定于应用程序的配置文件需要保持独立并位于/ App /文件夹中。
有没有办法可以在没有IoC容器的情况下完成它而不必将配置对象通过所有层次结构传递给模型(我在哪里实例化\ Fzaffa \ Sysyem \ Database对象)?
提前谢谢。