简体   繁体   English

使用Composer时如何处理配置文件和默认设置?

[英]How to handle config files and default settings when using Composer?

I was wondering what the best practices were for handling configuration files for your scripts when using Composer. 我想知道使用Composer时处理脚本配置文件的最佳实践是什么。

To elaborate, if I have a script that has several options or settings I'd usually just add them as variables or constants in a config.php file or something similar, and then require the file my script. 详细地说,如果我的脚本具有多个选项或设置,通常只需要将它们作为变量或常量添加到config.php文件或类似文件中,然后需要该文件作为我的脚本。 Or, if the script is a simple class then just use class properties... basic stuff, right? 或者,如果脚本是一个简单的类,则只需使用类属性...基本内容,对吧?

So, my question is, with the advent of PSR-4, autoloading, Composer, etc., what is the preferred way of doing this? 因此,我的问题是,随着PSR-4,自动加载,Composer等的出现,这样做的首选方式是什么?

It feels wrong to ask users to directly edit the file(s) in vendor/ (eg: to edit a config file or properties in a class, etc.). 要求用户直接在vendor /中编辑文件(例如:编辑配置文件或类中的属性等)感觉不对。 Plus, wouldn't those edits get overwritten on updates? 另外,这些编辑不会在更新后被覆盖吗?

I thought about using defined() in my script to look for certain constants, which the user could set in their own config files. 我考虑过在脚本中使用defined()查找某些常量,用户可以在自己的配置文件中设置这些常量。 This would probably work fine for smaller projects, but might become cumbersome and hard to scale. 这对于较小的项目可能会很好,但可能会变得麻烦且难以扩展。 For some scripts it might also be difficult to come up with sane defaults in the event that the constants aren't defined by the user. 对于某些脚本,如果常量不是由用户定义的,那么很难提供合理的默认值。

I also thought about using one of Composer's "hooks" to trigger a script that moves a config file somewhere like the project's root directory. 我还考虑过使用Composer的“钩子”之一来触发将配置文件移动到项目根目录等位置的脚本。 But then I hate to just drop a random config file in the user's project... 但是然后我讨厌只在用户的项目中删除一个随机的配置文件...

Am I overthinking this? 我在想这个吗? How do you guys typically handle this situation? 你们通常如何处理这种情况?

Don't have a configuration file. 没有配置文件。 Let the code which includes your project set configuration values at run time. 让包含您的项目的代码在运行时设置配置值。

If you are working in object oriented php you may want to take any required configuration parameters as arguments to your constructor or factory method, and provide setter methods for optional parameters, or parameters for which a sensible default value exists. 如果您使用面向对象的php,则可能需要将任何必需的配置参数用作构造函数或工厂方法的参数,并为可选参数或存在合理默认值的参数提供setter方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM