The cleanest way to read configuration settings from a PHP file and load all project code using a shell script

I am new to shell scripts, so you need some ideas on parsing a PHP file using a shell script.

Our PHP project, and I am improving our shell script, which is used to upload code to a production server.

There is one PHP configuration file production.settings.php that needs to be read at boot time, for several constants -

BASE_PATH (path to the project root on the prod server)
db_host , db_name , etc. (prod database database settings - for use to backup the database before loading)

Question

  • How to read the value of constants?

    They are defined as follows:

     define("BASE_PATH","/path/to/project/root"); 
  • How to read the first undocumented constant value?
    Note. A constant can be defined more than once in one file (suppose that it is possible - this can happen by mistake or line instances can be commented out).

So far I can only get the number of lines containing the define("BASE_PATH" line define("BASE_PATH" , using grep in my shell script -

 cd .. PROJECT_ROOT=$PWD result= grep -ic 'define("BASE_PATH",' $PROJECT_ROOT'/config/main.settings.php' echo "see"$result 
  • Is this parsing method good enough or will the yml file be better? Is there any / snippet command for this so that I can get the result by writing less code?

Update
Check out my other questions for more info on this: -
Manipulating an array (printed by php-cli) in a shell script ,
Assigning values ​​printed by the PHP CLI for shell variables ,
Initiation of dynamic variables (variable variables) in a bash shell script

+1
source share
3 answers

just do it with php, then call the shell script to call the php script.

Assuming you have a bunch of definitions defined in defs.php :

 define('NAME', 'JOHN'); define('HOBBY', 'FISHING'); 

then create php script get_defs.php :

 require_once 'defs.php'; $const = get_defined_constants(true); foreach($const['user'] as $k => $v) { echo "export $k=$v"; } 

then in your shell script run it like this:

 `php get_defs.php` 

What happens, get_defs.php will output a bunch of export KEY=VALUE , then the shell will run the commands that you entered in your php get_defs.php .

+1
source

Why don't you just use the PHP CLI ? What do you understand? Perhaps you could put the constants in the ini file and read them?

+1
source

If youre comforttable with PHP, then use PHP to write a shell script. IF you go along this route, I would move all the configuration settings to the configuration file ... INI, YAML, XML, whetever floats on your boat. Then I would change the load of the application that defines your constants to also read from this configuration file. Thus, you can use it both in your script and in the application without the need to change it.

0
source

Source: https://habr.com/ru/post/918184/


All Articles