php Generate Configuration File Based on Command Line Parameters
- 2021-11-29 23:16:34
- OfStack
Tools like npm, composer, etc., need to initialize the project and generate a configuration file of the project when they are used at the beginning. How is the principle of this function realized?
For example:
D:\>npm init --yes
Wrote to D:\package.json:
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"doc": "doc"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
In fact, it is very simple. Based on the command line parameters explained by php in the previous article, the following init branch can achieve similar functions
#!/usr/bin/php
<?php
function init(){
return file_put_contents( getcwd() . '/go.json', '{}' ) . 'bytes has written.' . 'config file has created';
}
$res = '';
if( $argc >= 2 ) {
$argv[1] == '-v' && $res = 'go version is 1.0';
$argv[1] == 'init' && $res = init();
}
echo $res . PHP_EOL;
ghostwu@ghostwu:~/mybin$ ls
go2
ghostwu@ghostwu:~/mybin$ go2 init
2bytes has written.config file has created
ghostwu@ghostwu:~/mybin$ ls
go2 go.json
ghostwu@ghostwu:~/mybin$ cat go.json
{}ghostwu@ghostwu:~/mybin$