gpt4 book ai didi

php 应用程序全局设置

转载 作者:可可西里 更新时间:2023-10-31 22:47:36 24 4
gpt4 key购买 nike

我已经阅读了我在 StackOverflow 上找到的关于这个主题的几乎所有问题,但找不到直接的答案。

这是我的代码:

应用类

<?php
class Application extends Settings {
public function __construct($env, $cacheDir, $configFile) {
self::$_env = $env;
self::$_cacheDir = $cacheDir;
self::$_config = $this->loadConfig($configFile) // reads configs from xml file into Config object
}

// other methods
}
?>

设置类:

<?php
class Settings {
protected static $_env = null;
protected static $_cacheDir = null;
protected static $_config = null;

public static function getEnv() {
return self::$_env;
}

public static function getCacheDir() {
return self::$_cacheDir;
}

public static function getConfig() {
return self::$_config;
}
}
?>

我从代码中的任何位置访问设置,如下所示:

<?php
var_dump(Settings::getEnv());
?>

我想从许多不同的地方访问设置。所有值只能设置一次且不能被覆盖(因此使用 __set 方法注册不起作用,因为我可以在应用程序过程的任何阶段的任何位置设置任何值)

问题:

像这样存储全局设置是好的做法吗?这种方法有什么缺点?也许有更好的方法来做到这一点?

谢谢你的回答

最佳答案

正如 Wrikken 在对您的问题的评论中指出的那样,您正在将全局状态引入您的应用程序。引用 Martin Fowler 的 Global State(PoEAA,第 482f 页):

Remember that any global data is always guilty until proven innocent.

简而言之意味着:避免它。不过,我将由您来研究该主题,因为详细讨论该问题超出了该问题的范围。

现在,为了更好的选择

假设您将所有流量路由到 index.php。然后,您可以简单地引导/构建满足该文件中的请求所需的所有组件。例如,像这样:

spl_autoload_register(
function($className) {
static $classMap = array(
'request' => '/path/from/here/to/Request.php',
… more mapping
);
require __DIR__ . $classMap[strtolower($className)];
}
);

$config = parse_ini_file(__DIR__ . '/path/from/here/to/config.ini');
foreach($config['env'] as $key => $val) {
ini_set($key, $val);
}

$router = new Router;
$router->registerActionForRoute(
'/product/list',
function($request, $response) use ($config) {
return new ProductListAction(
$request, $response
new ProductMapper(
new ProductGateway(
new MySqli($config['db']['host'], …),
new Cache($config['cache'], …)
),
new ProductBuilder;
)
);
}
);
$router->registerActionForRoute(…);
$router->execute(new Request($_GET, $_POST, $_SERVER), new Response);

当然,您更希望从单独的文件中包含自动加载器(因为您希望使用类似 https://github.com/theseer/Autoload 的内容自动生成它)。当然,您可以将路由器中的闭包替换为 Builder或工厂模式。我刚刚使用了 simplest thing possible .这样(希望)更容易理解。你可以查看http://silex-project.org/对于使用更复杂但类似方法的微框架。

这种方法的主要好处是每个组件从一开始到 Dependecy Injection 都能得到它需要的东西。 .这将使对代码进行单元测试变得更加容易,因为模拟依赖项和实现测试隔离要容易得多。

另一个好处是您将构造图和合作者图分开,因此您不会混淆它们 responsibility (就像您使用 Singleton 或以其他方式将 new 关键字放入应该是信息专家的类中一样。

关于php 应用程序全局设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6848455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com