对于 Unix 命令行脚本,单片方法允许非常高水平的可移植性。
使用单个(hashbang)脚本甚至允许将脚本转储到usr/bin
sudo cp myprog /usr/bin
/* (...) */
sudo cp myprog /usr/games
/* (...) */
这允许从任何地方、任何路径调用程序,只需键入myprog
,而不是/PATH/./myprog
. 确保它可以被信任!
我们必须格外小心路径。
关于路径的一些简单示例:
/* Create a folder in the home directory, named as the script name, if not existing. -*/
if (!is_dir($_SERVER["HOME"]."/".$_SERVER["SCRIPT_NAME"])){
@mkdir($_SERVER["HOME"]."/".$_SERVER["SCRIPT_NAME"]);
}
/* Program folder path: --------------------------------------------------------------*/
$PATH = $_SERVER["HOME"]."/".basename($_SERVER["SCRIPT_NAME"])."/";
/* Program running path, currently: --------------------------------------------------------------*/
$JOBPATH = getcwd();
处理POSIX 信号
/* Register cleaning actions at SIGINT ------------------------------------- */
function shutdown() {
// Perform actions at ctrl+c
echo "Good bye!";
exit;
}
/* Register resize at SIGWINCH ---------------------------------------------- */
function consoleResize() {
@ob_start;
$W = (int)exec("tput cols"); // Columns count
$H = (int)exec("tput lines"); // Lines count
@ob_end_clean();
// Shell window terminal resized!
}
/* Register action at SIGSTOP (Ctrl + z) ---------------------------------------------- */
function sigSTOP() {
// Program paused!
}
/* Register action at SIGCONT (Type fg to resume) ---------------------------------------------- */
function sigCONT() {
// Program restarted!
}
register_shutdown_function("shutdown");
declare(ticks = 1);
pcntl_signal(SIGINT, "shutdown");
pcntl_signal(SIGWINCH, "consoleResize");
这并不意味着我们必须在一个块中编写所有内容,而是将渲染合并到一个文件中允许在 unix 环境中使用许多额外的功能。
有很多话要说,php 作为 cli 脚本是一个了不起的野兽。