在PHP web应用程序中保存配置变量的最佳方法是什么?

时间:2021-10-18 20:07:33

I often switch between .NET and PHP development. With ASP.NET sites I save configuration information (e.g. connection strings, directories, application setting) in the web.config file which is appropriately protected and easy to access the values, etc.

我经常在。net和PHP开发之间切换。ASP。在web中保存配置信息(例如连接字符串、目录、应用程序设置)。配置文件,有适当的保护和易于访问的值等。

In PHP, I solve this with a class that has static methods for each variable:

在PHP中,我使用一个类来解决这个问题,该类对每个变量都有静态方法:

class webconfig {
    public static function defaultPageIdCode() {
        return 'welcome';
    }
}

The file is included by the app variables are accessed with a one-line:

app变量中包含的文件用一行访问:

$dp = webconfig::defaultPageIdCode();

And since PHP isn't compiled, it is easy to telnet in and change a value for a website anyway, so this solution works fairly well and gives me these two advantages:

由于PHP还没有编译,所以很容易通过telnet来更改一个网站的值,所以这个解决方案工作得很好,给了我这两个优点:

  • I can add logic to a config variable without breaking its interface with the application
  • 我可以向配置变量添加逻辑,而不会破坏它与应用程序的接口
  • these config variables appear as intellisense in my e.g. Eclipse, NetBeans, etc.
  • 这些配置变量在我的示例(如Eclipse、NetBeans等)中显示为intellisense。

But I can imagine there are other ways people solve saving web config settings in PHP which may have other advantages.

但是我可以想象,人们用PHP保存web配置设置的方法还有其他的优点。

Especially those who have experience with a number of PHP frameworks, what are other ways of saving config variables and their advantages and disadvantages?

特别是那些有很多PHP框架经验的人,还有什么其他的方法可以保存配置变量以及它们的优缺点?

11 个解决方案

#1


35  

I've decided to list all known methods along with their advantages and disadvantages.

我决定列出所有已知的方法及其优缺点。

I've marked this answer as a community wiki so collaboration is easier.

我将这个答案标记为一个社区wiki,因此协作更容易。


Global Constants

Assigning:

  • define('CONFIG_DIRECTIVE', 'value');
  • 定义(“CONFIG_DIRECTIVE”、“价值”);

Accessing:

  • $object = new MyObject(CONFIG_DIRECTIVE);
  • 美元= new MyObject对象(CONFIG_DIRECTIVE);

Advantages:

  • Has global scope.
  • 全局作用域。
  • Autocompleted by most IDEs.
  • 被大多数ide自动完成。
  • Has an agreed upon naming convention (UPPERCASE_UNDERSCORE_SEPARATED).
  • 已经商定了命名约定(UPPERCASE_UNDERSCORE_SEPARATED)。

Disadvantages:

  • Directives cannot contain arrays (prior to v7.0.0).
  • 指令不能包含数组(在v7.0.0之前)。

Special Notes:

  • Cannot be reassigned.
  • 不能重新分配。

Alternate Syntax Files

For example: XML, INI, YAML, etc.

例如:XML、INI、YAML等。

Assigning:

  • Simply edit the file in it's specific language. (For example, for INI files: config_directive = value.)
  • 只需编辑该文件的特定语言。(例如,对于INI文件:config_directive = value)。

Accessing:

  • The config file needs to be parsed. (For example, for INI's: parse_ini_file().)
  • 需要解析配置文件。(例如,对于INI的:parse_ini_file()))。

Advantages:

  • Most likely has a syntax more suited for a config file.
  • 很可能有一种更适合配置文件的语法。

Disadvantages:

  • Possible overhead of accessing and parsing the file.
  • 访问和解析文件的可能开销。

Array

Assigning:

  • $config['directive'] = 'value';
  • 美元配置(“指令”)=“价值”;

Accessing:

  • The cleanest method of accessing configuration values using this method is to pass the required values to the object that needs them on creation, or pass them to your container object and let it handle passing them out internally.
    • $object = new MyObject($config['directive']);
    • 美元= new MyObject对象($ config(“指令”));
    • $container = new MyContainer($config);
    • (容器= new MyContainer美元配置);
  • 使用此方法访问配置值的最干净的方法是将所需的值传递给在创建时需要它们的对象,或者将它们传递给容器对象,并让它处理在内部传递它们。美元= new MyObject对象($ config(“指令”));(容器= new MyContainer美元配置);

Advantages:

  • Directives can be arrays.
  • 指令可以是数组。

Disadvantages:

  • No autocompletion.
  • 没有自动完成。

Special Notes:

  • Variable collisions can occur. If this is a concern, name your array appropriately to avoid them.
  • 变量会发生碰撞。如果这是一个问题,请适当地命名数组以避免它们。

Class

Assigning:

  • There are many different class based implementations.
    • Static class.
      • myCfgObj::setDirective('DIRECTIVE', 'value');
      • myCfgObj:setDirective(“指令”,“价值”);
    • 静态类。myCfgObj:setDirective(“指令”,“价值”);
    • Instanced class.
      • myCfgObj->setDirective('DIRECTIVE', 'value');
      • myCfgObj - > setDirective(“指令”,“价值”);
    • 实例化类。myCfgObj - > setDirective(“指令”,“价值”);
  • 有许多不同的基于类的实现。静态类。myCfgObj:setDirective(“指令”,“价值”);实例化类。myCfgObj - > setDirective(“指令”,“价值”);

Accessing:

  • Again there are various class based implementations.
    • Static class.
      • $object = new MyObject(myCfgObj::getDirective('DIRECTIVE'));
      • $ = new MyObject对象(myCfgObj:getDirective(“指令”));
    • 静态类。$ = new MyObject对象(myCfgObj:getDirective(“指令”));
    • Instanced class.
      • $object = new MyObject(myCfgObj->getDirective('DIRECTIVE'));
      • $ = new MyObject对象(myCfgObj - > getDirective(“指令”));
    • 实例化类。$ = new MyObject对象(myCfgObj - > getDirective(“指令”));
  • 还有各种基于类的实现。静态类。$ = new MyObject对象(myCfgObj:getDirective(“指令”));实例化类。$ = new MyObject对象(myCfgObj - > getDirective(“指令”));

Advantages:

  • Can be autoloaded.
  • 可以自动装载。

Disadvantages:

  • Tends to be a bit verbose.
  • 有点啰嗦。
  • Can be hard to maintain if a container class is not being used.
  • 如果不使用容器类,则很难维护。

#2


23  

I tend to use a Settings static class in PHP, this is because

我倾向于在PHP中使用设置静态类,这是因为

  • It has a global scope.
  • 它具有全球范围。
  • You can enable/disable changes to protected configs.
  • 您可以启用/禁用对受保护配置的更改。
  • You can add any settings during anywhere within runtime.
  • 您可以在运行时的任何地方添加任何设置。
  • You can make the class automated to fetch public configs from a file/database.
  • 您可以使类自动从文件/数据库获取公共配置。

Example:

例子:

abstract class Settings
{
    static private $protected = array(); // For DB / passwords etc
    static private $public = array(); // For all public strings such as meta stuff for site

    public static function getProtected($key)
    {
        return isset(self::$protected[$key]) ? self::$protected[$key] : false;
    }

    public static function getPublic($key)
    {
        return isset(self::$public[$key]) ? self::$public[$key] : false;
    }

    public static function setProtected($key,$value)
    {
        self::$protected[$key] = $value;
    }

    public static function setPublic($key,$value)
    {
        self::$public[$key] = $value;
    }

    public function __get($key)
    {//$this->key // returns public->key
        return isset(self::$public[$key]) ? self::$public[$key] : false;
    }

    public function __isset($key)
    {
        return isset(self::$public[$key]);
    }
}

Then within your runtime, if you loaded this file first, followed by your database config file, your database config file would look like so:

然后在运行时内,如果您先加载这个文件,然后再加载数据库配置文件,那么您的数据库配置文件将如下所示:

<?php
Settings::setProtected('db_hostname', 'localhost');
Settings::setProtected('db_username', 'root');
Settings::setProtected('db_password', '');
Settings::setProtected('db_database', 'root');
Settings::setProtected('db_charset', 'UTF-8');
//...
echo Settings::getProtected('db_hostname'); // localhost
//...
Settings::setPublic('config_site_title', 'MySiteTitle');
Settings::setPublic('config_site_charset', 'UTF-8');
Settings::setPublic('config_site_root', 'http://localhost/dev/');

As you can see the we have a method __get that should only be allowed to grab public variables, An example of why we have this is as follows:

正如您所看到的,我们有一个方法__get,它应该只允许获取公共变量,我们有这样一个例子:

$template = new Template();
$template->assign('settings', new Settings());

Regardless the fact that we have used this object as a static object, the values should still stand so within the template you can now do, lets say.

不管我们使用这个对象作为一个静态对象的事实,这些值应该仍然在模板中,所以您现在可以这样做。

<html>
    <head>
        <?php echo isset($settings->config_site_title) ? $settings->config_site_title : 'Fallback Title'; ?>
    </head>
</html>

And this will only allow you to have access to the public data during the initialized period.

这将只允许您在初始化期间访问公共数据。

This can get a lot more complex but more system friendly, some examples:

这可以得到更复杂但更系统友好的例子:

  • A loadConfig method to automatically parse a config file, xml, php, yaml.
  • 一种loadConfig方法,用于自动解析配置文件、xml、php、yaml。
  • If you register an shutdown_function you can auto update the database with new settings.
  • 如果您注册了shutdown_function,您可以使用新的设置自动更新数据库。
  • You can auto-populate the class with config from that database.
  • 可以使用该数据库中的配置自动填充类。
  • You can implement iterators to make it compatible with looping.
  • 您可以实现迭代器,使其与循环兼容。
  • Lots more.
  • 更多。

This too me is by far the best methods to complete this job.

这也是完成这项工作的最好方法。

#3


4  

The way I do it is directly store them in an array and save the file as config.php

我的方法是直接将它们存储在一个数组中,并将文件保存为config.php

<?php

$config['dbname'] = "mydatabase";
$config['WebsiteName'] = "Fundoo Site";
$config['credits'] = true;
$config['version'] = "4.0.4";

?>

Thi is the way most PHP frameworks like Wordpress, etc do it.

这是大多数PHP框架(如Wordpress等)所采用的方法。

#4


2  

Note: "Best way" never exists. Every application and framework doing it their own style. While your example is doing the trick i think it's a little bit resource-heavy for a simple config file.

注:“最佳方式”从未存在。每个应用程序和框架都是自己的风格。当您的示例正在执行这个技巧时,我认为对于一个简单的配置文件来说,这有点耗费资源。

  • You can do it with single variables like Amber pointed out
  • 你可以用单个变量,如Amber指出的
  • You can do it with arrays this is the most common approach and you can always easily edit your config file.
  • 你可以用数组来做,这是最常见的方法,你可以很容易地编辑你的配置文件。
  • You can do it with .ini files that PHP easily parsing
  • 您可以使用PHP易于解析的.ini文件来实现这一点

Edit:

编辑:

Edward please take a look at parse_ini_file's examples. You can load the .ini file with a simple command then you can use the variables in a class like in your example.

Edward,请看看parse_ini_file的例子。您可以使用简单的命令加载.ini文件,然后您可以在您的示例中使用类中的变量。

#5


2  

There are pretty much possibilities I think, but the most common methods are storing as plain text in files like .csv, .ini, .xml. With little tricks you can protect these files, so that no one can load the files directly.

我认为有很多可能性,但最常见的方法是将纯文本存储在.csv、.ini和.xml等文件中。使用小技巧可以保护这些文件,这样就没有人可以直接加载文件了。

an INI-File example:

一个ini文件的例子:

;<?php die(); ?>
[config1]
var1 = 'value1';
var2 = 'value2';
...
[config2]
...

The ; is considered a comment in ini files. So when you read in the file with an ini-parser, this line will be ignored. If someone accesses the file directly via url the die()-function will be executed. This works only, if the INI-file wears a file-extension like .php so that the server knows that this should be executed and not diplayed as plain text.

的;在ini文件中被视为注释。因此,当您在文件中读取一个ini-parser时,这条线将被忽略。如果有人直接通过url访问文件,die()函数将被执行。只有当ini文件具有.php这样的文件扩展名时,服务器才知道应该执行这个操作,而不是作为纯文本进行diplay。

Possible disadvantage of most file-base-config-storages are problems with some utf8-characters.

大多数基于文件的-config-storage的可能缺点是一些utf8字符的问题。

Zend_Config is a component of the Zend-Framework, which provides possibilities for several storage-adapters with an easy to use api.

Zend_Config是Zend-Framework的一个组件,它为具有易于使用的api的多个存储适配器提供了可能性。

#6


1  

In PHP I always use a ".htaccess" to protect my config file (Double protection)

在PHP中,我总是使用“。htaccess保护我的配置文件(双重保护)

#7


1  

Since PHP is able to use OO, I like to go with a "Config class":

因为PHP可以使用OO,所以我喜欢使用“Config类”:

class Config
{
    /**
     * ---------------------------------
     * Database - Access
     * --------------------------------- 
     */

    /**
     * @var String
     */
    const DB_DRIVER = 'pgsql';

    const DB_USER = 'postgres';

    const DB_PASSWORD = 'postgres';

    const DB_NAME = 'postgres';
}

It is easy accessable with Config::DB_DRIVER. No need to include the file since the application autoloader will do that for you. Of course, protecting the file still needs to be done.

配置::DB_DRIVER很容易访问。不需要包含文件,因为应用程序autoloader会为您做这些。当然,保护文件仍然需要完成。

#8


0  

Telnet? OMG I've fallen into a timewarp and arrived in 1992!

远程登录吗?我的天啊,我真是落伍了,1992年才到!

But seriously, IIRC there are tools which allow asp.net (and other languages) to parse session data - which is just a serialized php array. I'd have a go at implementing the global settings as a sort of shadow session within PHP. Even if you don't store your config settings as a serialized PHP array, you could map them into the session at runtime using your own session handler.

但说真的,IIRC有一些工具可以让asp.net(和其他语言)解析会话数据——这只是一个序列化的php数组。我将尝试将全局设置实现为PHP中的一种影子会话。即使不将配置设置存储为序列化的PHP数组,也可以使用自己的会话处理程序在运行时将它们映射到会话中。

In terms of where you store the data - that's a more tricky one when you're presumably running on a Microsoft platform. Obviously you don't want the expense of disk access for every request. Although NT does some disk caching it's not (IME) quite as effective as other OS. Memcached appears to be one solution to this. It does appear to be usable from asp.net.

就数据存储的位置而言——当你在微软平台上运行时,这是一个更棘手的问题。显然,您不希望为每个请求花费磁盘访问的费用。虽然NT做了一些磁盘缓存,但它并不像其他OS那样有效。Memcached似乎是一种解决方案。它看起来确实可以在asp.net中使用。

HTH

HTH

#9


0  

The usual route is to use define:

通常的方法是使用define:

define('MYSQL_USER', 'ROOT');

and access it all over the application via MYSQL_USER :

通过MYSQL_USER访问整个应用程序:

$user = MYSQL_USER;

However arrays are not supported in this way.

但是不支持数组。

#10


0  

There are few possibilities:

有几种可能性:

  1. You can use config file (ini, json, xml or yaml). For ini you have parse_ini_file, for JSON there is json_decode (+file_get_contents), for YAML you have to use external library (search for sfYaml)

    可以使用配置文件(ini、json、xml或yaml)。对于ini,有parse_ini_file,对于JSON,有json_decode (+file_get_contents),对于YAML,必须使用外部库(搜索sfYaml)

  2. You can have a config file with variables or constants (better for immutable config and accessible in all scopes), which you includes in your script:

    您可以有一个带有变量或常量的配置文件(对于不可变的配置更好,并且可以在所有范围中访问),您在脚本中包括:

    define('ROOT_DIR', '\home\www');

    定义(' ROOT_DIR ',' \ \ www回家');

    $sRootDir = '\home\www';

    美元sRootDir = ' \ \ www回家';

If you are OO-oriented, you can wrap it in class, as properties - you do not have getter method for every property, you can just have:

如果你是面向oo的,你可以在类中把它包装成属性——你没有针对每个属性的getter方法,你只需要:

class Config
{
    public $var1 = 'xxx';
    public $var2 = 'yyy';
}

($c = new Config(); print $c->var1)

($ c =新配置();print $ c - > var1)

or

static class Config
{
    public static $var1 = 'xxx';
    public static $var2 = 'yyy';
}

(print c::$var1)

(打印c::$ var1)

The best is to have registry-type class, implementing singleton pattern and capable to read config from given file.

最好是拥有注册类型的类,实现单例模式,并且能够从给定的文件中读取配置。

#11


0  

In order to be testable, I use a Config class that holds the actual configuration data and an AppConfig static class that holds a reference to a Config object loaded at bootstrap from application wide configuration files (dependency injected at bootstrap). In the tests environment, I only change the Config object. See https://github.com/xprt64/Config

为了可测试,我使用一个配置类来保存实际的配置数据,以及一个AppConfig静态类来保存对从应用程序范围的配置文件引导加载的配置对象的引用(在引导时注入的依赖项)。在测试环境中,我只更改配置对象。参见https://github.com/xprt64/Config

#1


35  

I've decided to list all known methods along with their advantages and disadvantages.

我决定列出所有已知的方法及其优缺点。

I've marked this answer as a community wiki so collaboration is easier.

我将这个答案标记为一个社区wiki,因此协作更容易。


Global Constants

Assigning:

  • define('CONFIG_DIRECTIVE', 'value');
  • 定义(“CONFIG_DIRECTIVE”、“价值”);

Accessing:

  • $object = new MyObject(CONFIG_DIRECTIVE);
  • 美元= new MyObject对象(CONFIG_DIRECTIVE);

Advantages:

  • Has global scope.
  • 全局作用域。
  • Autocompleted by most IDEs.
  • 被大多数ide自动完成。
  • Has an agreed upon naming convention (UPPERCASE_UNDERSCORE_SEPARATED).
  • 已经商定了命名约定(UPPERCASE_UNDERSCORE_SEPARATED)。

Disadvantages:

  • Directives cannot contain arrays (prior to v7.0.0).
  • 指令不能包含数组(在v7.0.0之前)。

Special Notes:

  • Cannot be reassigned.
  • 不能重新分配。

Alternate Syntax Files

For example: XML, INI, YAML, etc.

例如:XML、INI、YAML等。

Assigning:

  • Simply edit the file in it's specific language. (For example, for INI files: config_directive = value.)
  • 只需编辑该文件的特定语言。(例如,对于INI文件:config_directive = value)。

Accessing:

  • The config file needs to be parsed. (For example, for INI's: parse_ini_file().)
  • 需要解析配置文件。(例如,对于INI的:parse_ini_file()))。

Advantages:

  • Most likely has a syntax more suited for a config file.
  • 很可能有一种更适合配置文件的语法。

Disadvantages:

  • Possible overhead of accessing and parsing the file.
  • 访问和解析文件的可能开销。

Array

Assigning:

  • $config['directive'] = 'value';
  • 美元配置(“指令”)=“价值”;

Accessing:

  • The cleanest method of accessing configuration values using this method is to pass the required values to the object that needs them on creation, or pass them to your container object and let it handle passing them out internally.
    • $object = new MyObject($config['directive']);
    • 美元= new MyObject对象($ config(“指令”));
    • $container = new MyContainer($config);
    • (容器= new MyContainer美元配置);
  • 使用此方法访问配置值的最干净的方法是将所需的值传递给在创建时需要它们的对象,或者将它们传递给容器对象,并让它处理在内部传递它们。美元= new MyObject对象($ config(“指令”));(容器= new MyContainer美元配置);

Advantages:

  • Directives can be arrays.
  • 指令可以是数组。

Disadvantages:

  • No autocompletion.
  • 没有自动完成。

Special Notes:

  • Variable collisions can occur. If this is a concern, name your array appropriately to avoid them.
  • 变量会发生碰撞。如果这是一个问题,请适当地命名数组以避免它们。

Class

Assigning:

  • There are many different class based implementations.
    • Static class.
      • myCfgObj::setDirective('DIRECTIVE', 'value');
      • myCfgObj:setDirective(“指令”,“价值”);
    • 静态类。myCfgObj:setDirective(“指令”,“价值”);
    • Instanced class.
      • myCfgObj->setDirective('DIRECTIVE', 'value');
      • myCfgObj - > setDirective(“指令”,“价值”);
    • 实例化类。myCfgObj - > setDirective(“指令”,“价值”);
  • 有许多不同的基于类的实现。静态类。myCfgObj:setDirective(“指令”,“价值”);实例化类。myCfgObj - > setDirective(“指令”,“价值”);

Accessing:

  • Again there are various class based implementations.
    • Static class.
      • $object = new MyObject(myCfgObj::getDirective('DIRECTIVE'));
      • $ = new MyObject对象(myCfgObj:getDirective(“指令”));
    • 静态类。$ = new MyObject对象(myCfgObj:getDirective(“指令”));
    • Instanced class.
      • $object = new MyObject(myCfgObj->getDirective('DIRECTIVE'));
      • $ = new MyObject对象(myCfgObj - > getDirective(“指令”));
    • 实例化类。$ = new MyObject对象(myCfgObj - > getDirective(“指令”));
  • 还有各种基于类的实现。静态类。$ = new MyObject对象(myCfgObj:getDirective(“指令”));实例化类。$ = new MyObject对象(myCfgObj - > getDirective(“指令”));

Advantages:

  • Can be autoloaded.
  • 可以自动装载。

Disadvantages:

  • Tends to be a bit verbose.
  • 有点啰嗦。
  • Can be hard to maintain if a container class is not being used.
  • 如果不使用容器类,则很难维护。

#2


23  

I tend to use a Settings static class in PHP, this is because

我倾向于在PHP中使用设置静态类,这是因为

  • It has a global scope.
  • 它具有全球范围。
  • You can enable/disable changes to protected configs.
  • 您可以启用/禁用对受保护配置的更改。
  • You can add any settings during anywhere within runtime.
  • 您可以在运行时的任何地方添加任何设置。
  • You can make the class automated to fetch public configs from a file/database.
  • 您可以使类自动从文件/数据库获取公共配置。

Example:

例子:

abstract class Settings
{
    static private $protected = array(); // For DB / passwords etc
    static private $public = array(); // For all public strings such as meta stuff for site

    public static function getProtected($key)
    {
        return isset(self::$protected[$key]) ? self::$protected[$key] : false;
    }

    public static function getPublic($key)
    {
        return isset(self::$public[$key]) ? self::$public[$key] : false;
    }

    public static function setProtected($key,$value)
    {
        self::$protected[$key] = $value;
    }

    public static function setPublic($key,$value)
    {
        self::$public[$key] = $value;
    }

    public function __get($key)
    {//$this->key // returns public->key
        return isset(self::$public[$key]) ? self::$public[$key] : false;
    }

    public function __isset($key)
    {
        return isset(self::$public[$key]);
    }
}

Then within your runtime, if you loaded this file first, followed by your database config file, your database config file would look like so:

然后在运行时内,如果您先加载这个文件,然后再加载数据库配置文件,那么您的数据库配置文件将如下所示:

<?php
Settings::setProtected('db_hostname', 'localhost');
Settings::setProtected('db_username', 'root');
Settings::setProtected('db_password', '');
Settings::setProtected('db_database', 'root');
Settings::setProtected('db_charset', 'UTF-8');
//...
echo Settings::getProtected('db_hostname'); // localhost
//...
Settings::setPublic('config_site_title', 'MySiteTitle');
Settings::setPublic('config_site_charset', 'UTF-8');
Settings::setPublic('config_site_root', 'http://localhost/dev/');

As you can see the we have a method __get that should only be allowed to grab public variables, An example of why we have this is as follows:

正如您所看到的,我们有一个方法__get,它应该只允许获取公共变量,我们有这样一个例子:

$template = new Template();
$template->assign('settings', new Settings());

Regardless the fact that we have used this object as a static object, the values should still stand so within the template you can now do, lets say.

不管我们使用这个对象作为一个静态对象的事实,这些值应该仍然在模板中,所以您现在可以这样做。

<html>
    <head>
        <?php echo isset($settings->config_site_title) ? $settings->config_site_title : 'Fallback Title'; ?>
    </head>
</html>

And this will only allow you to have access to the public data during the initialized period.

这将只允许您在初始化期间访问公共数据。

This can get a lot more complex but more system friendly, some examples:

这可以得到更复杂但更系统友好的例子:

  • A loadConfig method to automatically parse a config file, xml, php, yaml.
  • 一种loadConfig方法,用于自动解析配置文件、xml、php、yaml。
  • If you register an shutdown_function you can auto update the database with new settings.
  • 如果您注册了shutdown_function,您可以使用新的设置自动更新数据库。
  • You can auto-populate the class with config from that database.
  • 可以使用该数据库中的配置自动填充类。
  • You can implement iterators to make it compatible with looping.
  • 您可以实现迭代器,使其与循环兼容。
  • Lots more.
  • 更多。

This too me is by far the best methods to complete this job.

这也是完成这项工作的最好方法。

#3


4  

The way I do it is directly store them in an array and save the file as config.php

我的方法是直接将它们存储在一个数组中,并将文件保存为config.php

<?php

$config['dbname'] = "mydatabase";
$config['WebsiteName'] = "Fundoo Site";
$config['credits'] = true;
$config['version'] = "4.0.4";

?>

Thi is the way most PHP frameworks like Wordpress, etc do it.

这是大多数PHP框架(如Wordpress等)所采用的方法。

#4


2  

Note: "Best way" never exists. Every application and framework doing it their own style. While your example is doing the trick i think it's a little bit resource-heavy for a simple config file.

注:“最佳方式”从未存在。每个应用程序和框架都是自己的风格。当您的示例正在执行这个技巧时,我认为对于一个简单的配置文件来说,这有点耗费资源。

  • You can do it with single variables like Amber pointed out
  • 你可以用单个变量,如Amber指出的
  • You can do it with arrays this is the most common approach and you can always easily edit your config file.
  • 你可以用数组来做,这是最常见的方法,你可以很容易地编辑你的配置文件。
  • You can do it with .ini files that PHP easily parsing
  • 您可以使用PHP易于解析的.ini文件来实现这一点

Edit:

编辑:

Edward please take a look at parse_ini_file's examples. You can load the .ini file with a simple command then you can use the variables in a class like in your example.

Edward,请看看parse_ini_file的例子。您可以使用简单的命令加载.ini文件,然后您可以在您的示例中使用类中的变量。

#5


2  

There are pretty much possibilities I think, but the most common methods are storing as plain text in files like .csv, .ini, .xml. With little tricks you can protect these files, so that no one can load the files directly.

我认为有很多可能性,但最常见的方法是将纯文本存储在.csv、.ini和.xml等文件中。使用小技巧可以保护这些文件,这样就没有人可以直接加载文件了。

an INI-File example:

一个ini文件的例子:

;<?php die(); ?>
[config1]
var1 = 'value1';
var2 = 'value2';
...
[config2]
...

The ; is considered a comment in ini files. So when you read in the file with an ini-parser, this line will be ignored. If someone accesses the file directly via url the die()-function will be executed. This works only, if the INI-file wears a file-extension like .php so that the server knows that this should be executed and not diplayed as plain text.

的;在ini文件中被视为注释。因此,当您在文件中读取一个ini-parser时,这条线将被忽略。如果有人直接通过url访问文件,die()函数将被执行。只有当ini文件具有.php这样的文件扩展名时,服务器才知道应该执行这个操作,而不是作为纯文本进行diplay。

Possible disadvantage of most file-base-config-storages are problems with some utf8-characters.

大多数基于文件的-config-storage的可能缺点是一些utf8字符的问题。

Zend_Config is a component of the Zend-Framework, which provides possibilities for several storage-adapters with an easy to use api.

Zend_Config是Zend-Framework的一个组件,它为具有易于使用的api的多个存储适配器提供了可能性。

#6


1  

In PHP I always use a ".htaccess" to protect my config file (Double protection)

在PHP中,我总是使用“。htaccess保护我的配置文件(双重保护)

#7


1  

Since PHP is able to use OO, I like to go with a "Config class":

因为PHP可以使用OO,所以我喜欢使用“Config类”:

class Config
{
    /**
     * ---------------------------------
     * Database - Access
     * --------------------------------- 
     */

    /**
     * @var String
     */
    const DB_DRIVER = 'pgsql';

    const DB_USER = 'postgres';

    const DB_PASSWORD = 'postgres';

    const DB_NAME = 'postgres';
}

It is easy accessable with Config::DB_DRIVER. No need to include the file since the application autoloader will do that for you. Of course, protecting the file still needs to be done.

配置::DB_DRIVER很容易访问。不需要包含文件,因为应用程序autoloader会为您做这些。当然,保护文件仍然需要完成。

#8


0  

Telnet? OMG I've fallen into a timewarp and arrived in 1992!

远程登录吗?我的天啊,我真是落伍了,1992年才到!

But seriously, IIRC there are tools which allow asp.net (and other languages) to parse session data - which is just a serialized php array. I'd have a go at implementing the global settings as a sort of shadow session within PHP. Even if you don't store your config settings as a serialized PHP array, you could map them into the session at runtime using your own session handler.

但说真的,IIRC有一些工具可以让asp.net(和其他语言)解析会话数据——这只是一个序列化的php数组。我将尝试将全局设置实现为PHP中的一种影子会话。即使不将配置设置存储为序列化的PHP数组,也可以使用自己的会话处理程序在运行时将它们映射到会话中。

In terms of where you store the data - that's a more tricky one when you're presumably running on a Microsoft platform. Obviously you don't want the expense of disk access for every request. Although NT does some disk caching it's not (IME) quite as effective as other OS. Memcached appears to be one solution to this. It does appear to be usable from asp.net.

就数据存储的位置而言——当你在微软平台上运行时,这是一个更棘手的问题。显然,您不希望为每个请求花费磁盘访问的费用。虽然NT做了一些磁盘缓存,但它并不像其他OS那样有效。Memcached似乎是一种解决方案。它看起来确实可以在asp.net中使用。

HTH

HTH

#9


0  

The usual route is to use define:

通常的方法是使用define:

define('MYSQL_USER', 'ROOT');

and access it all over the application via MYSQL_USER :

通过MYSQL_USER访问整个应用程序:

$user = MYSQL_USER;

However arrays are not supported in this way.

但是不支持数组。

#10


0  

There are few possibilities:

有几种可能性:

  1. You can use config file (ini, json, xml or yaml). For ini you have parse_ini_file, for JSON there is json_decode (+file_get_contents), for YAML you have to use external library (search for sfYaml)

    可以使用配置文件(ini、json、xml或yaml)。对于ini,有parse_ini_file,对于JSON,有json_decode (+file_get_contents),对于YAML,必须使用外部库(搜索sfYaml)

  2. You can have a config file with variables or constants (better for immutable config and accessible in all scopes), which you includes in your script:

    您可以有一个带有变量或常量的配置文件(对于不可变的配置更好,并且可以在所有范围中访问),您在脚本中包括:

    define('ROOT_DIR', '\home\www');

    定义(' ROOT_DIR ',' \ \ www回家');

    $sRootDir = '\home\www';

    美元sRootDir = ' \ \ www回家';

If you are OO-oriented, you can wrap it in class, as properties - you do not have getter method for every property, you can just have:

如果你是面向oo的,你可以在类中把它包装成属性——你没有针对每个属性的getter方法,你只需要:

class Config
{
    public $var1 = 'xxx';
    public $var2 = 'yyy';
}

($c = new Config(); print $c->var1)

($ c =新配置();print $ c - > var1)

or

static class Config
{
    public static $var1 = 'xxx';
    public static $var2 = 'yyy';
}

(print c::$var1)

(打印c::$ var1)

The best is to have registry-type class, implementing singleton pattern and capable to read config from given file.

最好是拥有注册类型的类,实现单例模式,并且能够从给定的文件中读取配置。

#11


0  

In order to be testable, I use a Config class that holds the actual configuration data and an AppConfig static class that holds a reference to a Config object loaded at bootstrap from application wide configuration files (dependency injected at bootstrap). In the tests environment, I only change the Config object. See https://github.com/xprt64/Config

为了可测试,我使用一个配置类来保存实际的配置数据,以及一个AppConfig静态类来保存对从应用程序范围的配置文件引导加载的配置对象的引用(在引导时注入的依赖项)。在测试环境中,我只更改配置对象。参见https://github.com/xprt64/Config