像npm, composer等工具,在開始使用的使用,都需要初始化項目,生成一個項目的配置文件。這種功能的原理是怎么實現(xiàn)的呢?
比如:
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其實很簡單,在之前這篇文章php解釋命令行的參數(shù)的基礎(chǔ)上,加上下面的init分支,即可實現(xiàn)類似的功能
#!/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$