假设我有这样的事情:
<?php
namespace Twitter;
class Twitter {
function __construct()
{
$config = array ('api' => 'something', 'api_url' => 'something2');
}
// some code goes here
}
class TwitterConnection {
function __construct()
{
$config = array ('api' => 'something', 'api_url' => 'something2');
}
// some code goes here
}
?>
Run Code Online (Sandbox Code Playgroud)
等等 - 将会有更多使用$ config变量的类.
现在,问题是:如何只定义一次配置,并使其可以在所有类中访问?
谢谢
您可以创建一个从数据源(ini,db,php文件...)读取的配置对象并填充自身.然后给它一个getter,这样你就可以获得存储在其中的配置属性.
有点像 Config::get('someProperty')
设置此对象后,可以将其传递给类的构造函数,以便在内部使用.
class Twitter {
function __construct($config) {
$state = $config->get('someState');
}
}
Run Code Online (Sandbox Code Playgroud)
你也可以简单地在你的类中使用它,而不是通过使它成为一个静态类来注入它(你也可以像创建一个新实例一样).
class Twitter {
function __construct() {
//Don't recommend this, better to inject it.
$state = Config::get('someState');
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
使用硬编码数组的最简单的配置类看起来像这样.我再次建议您从代码中移出配置.
class Config {
private $opts = array();
public function __construct() {
/**
* Ideally opts should be coming from some kind of easy to
* access configuration file
*
*/
$this->opts = array ('api' => 'something', 'api_url' => 'something2');
}
public function get($key) {
if (isset($this->opts[$key])) {
return $this->opts[$key];
}
return false;
}
}
class Twitter {
function __construct($config) {
echo $config->get('api');
}
}
$config = new Config();
new Twitter($config);
Run Code Online (Sandbox Code Playgroud)
您还可以稍微更改一下类,以便它可以在不需要自身实例的情况下工作.
| 归档时间: |
|
| 查看次数: |
806 次 |
| 最近记录: |