Mike Everhart
Mike Everhart

Reputation: 408

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.

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. 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?

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.). 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. 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. 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?

Upvotes: 2

Views: 1544

Answers (1)

bdsl
bdsl

Reputation: 322

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.

Upvotes: 0

Related Questions