Главная Новости

Управление оболочкой командной строки в PHP

Опубликовано: 05.09.2018

видео Управление оболочкой командной строки в PHP

Linux - Терминал в Ubuntu, shell, bash, базовые команды, права доступа к файлам.

Этот пакет php-классов может быть использован для создания и управления оболочкой командной строки в чистом PHP.



Он может читать команды из стандартного ввода и выполнять опознанные команды с помощью отдельных классов.

Список распознаваемых команд можно настроить путем регистрации PHP классов, которые реализуют новый пользовательский обработчик команды.

Основной класс запускает цикл обработки событий, который отображает подсказки, читает команды из стандартного ввода и отправляет вызовы команд классам для последующей обработки этих команд. Цикл заканчивается, когда команды выполнены.


Работа в командной строке [GeekBrains]

Несколько встроенных пользовательских классов обработки команд, предоставлены для выполнения действий, таких как: перечисление всех зарегистрированных команд, предоставление справки и примера для использования команды.

Лицензия LGPL.

Системные требования скрипта:

PHP не младше 5.0 версии.

Исходник скрипта:

/* * Project: Absynthe Shell * File: AShell.class.php * Author: Sylvain 'Absynthe' Rabot <[email protected]> * Webste: http://aforge.abstraction.fr/ * Version: alpha 1 * Date: 08/07/2007 * License: LGPL */ /** * Interface for ASCommand */ interface I_ASCommand { public function init(); public function setName($name); public function getName(); public function setHelp($help); public function getHelp(); public function setDescription($description); public function getDescription(); public function setRawCommand($raw); public function getRawCommand(); public function setArguments($arguments); public function getArguments(); public function setCommunicator(&$communicator); public function prompt($text); public function write($text); public function listen($length = 1024); public function newLine($number = 1); public function tab($number = 1); } /** * Implementation of I_ASCommand */ class ASCommand implements I_ASCommand { public $prompt; public $name; public $help; public $description; public $rawCommand; public $arguments; public $communicator; /** * Initialize object before start() if __construct() didn't do the work */ public function init() { if (empty($this->name)) $this->name = next(explode('::', __CLASS__)); if (empty($this->prompt)) $this->prompt = $this->name.'$ '; } /** * Sets the name of the command * * @param string $name */ public function setName($name) { $this->name = $name; } /** * Returns the name of the command * * @return string */ public function getName() { return strtolower($this->name); } /** * Sets the help of the command * * @param string $help */ public function setHelp($help) { $this->help = $help; } /** * Returns the help of the command * * @return mixed */ public function getHelp() { if (!empty($this->help)) return $this->help; else return false; } /** * Sets the description of the command * * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * Returns the description of the command * * @return mixed */ public function getDescription() { if (!empty($this->description)) return $this->description; else return false; } /** * Sets the whole command used by the user * * @param string $raw */ public function setRawCommand($raw) { $this->rawCommand = $raw; } /** * Returns the whole command used by the user * * @return string */ public function getRawCommand() { return $this->getArguments(); } /** * Sets the argument list used by the user * * @param string $arguments */ public function setArguments($arguments) { $this->arguments = $arguments; } /** * Returns the argument list used by the user * * @return string */ public function getArguments() { return $this->getArguments(); } /** * Sets the communicator handler * * @param array $communicator */ public function setCommunicator(&$communicator) { $this->communicator = &$communicator; } /** * Displays a prompt and returns user's request * * @param string $text * @param int $length * @return string */ public function prompt($text, $length = 1042) { $this->write($this->prompt); return $this->listen($length); } /** * Display a string * * @param string $string */ public function write($string) { fwrite(STDOUT, $string); } /** * Returns user's request * * @param unknown_type $length * @return unknown */ public function listen($length = 1024) { return trim(fread(STDIN, $length)); } /** * Display requested number of lines * * @param int $number */ public function newLine($number = 1) { for ($x = 0; $x < $number; $x++) fwrite(STDOUT, "\n"); } /** * Display requested number of tabulations * * @param int $number */ public function tab($number = 1) { for ($x = 0; $x < $number; $x++) fwrite(STDOUT, "\t"); } } /** * Exemple of command for AShell */ class hello extends ASCommand { public function __construct() { $this->name = "hello"; $this->prompt = "hello$ "; $this->description = "This command say HELLO WORLD!"; } public function start() { $this->communicator['hello'] = 'we said hello !'; $this->newLine(); $this->write("HELLO WOLRD !!!"); $this->newLine(2); } } /** * AShell command : Help command for AShell */ class help extends ASCommand { public function __construct() { $this->name = "help"; $this->prompt = "help$ "; $this->description = "This command show you the HELP"; } public function start() { $this->communicator['help'] = 'we have shown the help !'; $askedHelp = strtolower(next(explode(' ', $this->rawCommand))); if (empty($askedHelp)) { $this->newLine(); $this->write("To view the help of a command run : help <command>"); $this->newLine(2); } else if (array_key_exists($askedHelp, $this->arguments['methods'])) { if ($this->arguments['methods'][$askedHelp]->getHelp() !== false) { $this->newLine(); $this->write("HELP FOR $askedHelp :"); $this->newLine(2); $this->write($this->arguments['methods'][$askedHelp]->getHelp()); $this->newLine(2); } else { $this->newLine(); $this->write("HELP FOR $askedHelp :"); $this->newLine(2); $this->write("This command does not have any help."); $this->newLine(2); } } else { $this->newLine(); $this->write("HELP FOR $askedHelp :"); $this->newLine(2); $this->write("This command does not have any help."); $this->newLine(2); } } } /** * AShell command : Displays all the command available */ class commandlist extends ASCommand { public function __construct() { $this->name = "commandlist"; $this->prompt = "commandlist$ "; $this->description = "This command show you the list of all command you can use"; } public function start() { $this->newLine(); $this->write("List of commands available : "); $this->newLine(2); foreach ($this->arguments['methods'] as $key => &$value) { $this->tab(); if ($value->getDescription() !== false) $this->write('+ '.$key.' : '.$value->getDescription()); else $this->write('+ '.$key); $this->newLine(); } $this->newLine(); } } /** * AShell command : Displays the content of the communicator */ class communicator extends ASCommand { public function __construct() { $this->name = "communicator"; $this->prompt = "communicator$ "; $this->description = "This command show you the communicator"; } public function start() { $this->newLine(); $this->write("Content of the communicator : "); $this->newLine(2); foreach ($this->communicator as $key => $value) { $this->tab(); $this->write('+ '.$key.' : '.$value); $this->newLine(); } $this->newLine(); } } /** * Command Handler */ class AShell { private $prompt = 'ashell'; private $methods = array(); private $exit = array('exit', 'quit', 'stop'); private $common = array('help', 'hello', 'communicator', 'commandlist'); public $communicator = array(); /** * Constructor * * @param string $prompt */ public function __construct($prompt = '') { if (!empty($prompt)) $this->prompt = $prompt; foreach ($this->common as $command) { $temp[] = new $command(); $this->registerCommand($temp[count($temp) - 1]); } } /** * Adds a command to the handler * * @param I_ASCommand $method */ public function registerCommand(I_ASCommand &$method) { $this->methods[$method->getName()] = $method; } /** * Runs the handler */ public function start() { $run = true; /* Compute -------- */ while ($run) { /* Initialisation of request -------- */ $raw = $this->prompt(); $method = $this->parseMethod($raw); $arguments = $this->parseArguments($raw); /* Common Comand -------- */ if (in_array($method, $this->common)) { $this->methods[$method]->setRawCommand($raw); $this->methods[$method]->setArguments(array('agrs' => $arguments, 'methods' => $this->methods)); $this->methods[$method]->setCommunicator($this->communicator); $this->methods[$method]->init(); $this->methods[$method]->start(); } /* Exit command -------- */ else if (in_array($method, $this->exit)) { $run = false; } /* Other command -------- */ else { /* Command not found -------- */ if (!array_key_exists($method, $this->methods)) { $this->write("The requested method ($method) is not implemented or is not loaded."); $this->newLine(); } /* Command found -------- */ else { try { $this->methods[$method]->setRawCommand($raw); $this->methods[$method]->setArguments($arguments); $this->methods[$method]->setCommunicator($this->communicator); $this->methods[$method]->init(); $this->methods[$method]->start(); } catch (Exception $e) { $this->write("AN ERROR HAPPENED DURING EXECUTION OF : $method"); $this->newLine(); $this->write($e->getMessage()); } } } } } /** * Returns the name a the command requested by the user * * @param string $raw * @return string */ private function parseMethod($raw) { $exploded = explode(' ', $raw); return strtolower($exploded[0]); } /** * Return the list of arguments requested by the user * * @param string $raw * @return array */ private function parseArguments($raw) { $arguments = array(); preg_match_all("#(-|--)([a-zA-Z0-9][a-zA-Z0-9\_-]*)(\=([a-zA-Z0-9\_-]+)|\=\"(.*)\"|\s+([a-zA-Z0-9][a-zA-Z0-9\_-]*))?#", $raw, $match, PREG_SET_ORDER); foreach ($match as $key => $value) { /* Mask : -P or --p -------- */ if (count($value) === 3) { $arguments[$value[0]] = true; } /* Mask: --password="my password" -------- */ else if (count($value) === 5) { $arguments[$value[1].$value[2]] = $value[4]; } /* Mask: --password=my_password -------- */ else if (count($value) === 6) { $arguments[$value[1].$value[2]] = $value[5]; } /* Mask : -P password -------- */ else if (count($value) === 7) { $arguments[$value[1].$value[2]] = $value[6]; } } return $arguments; } /** * Displays a prompt and return user's request * * @return string */ private function prompt() { fwrite(STDOUT, $this->prompt."$ "); return trim(fread(STDIN, 1024)); } /** * Displays a text * * @param string $string */ private function write($string) { fwrite(STDOUT, $string); } /** * Displays requested number of lines * * @param int $number */ private function newLine($number = 1) { for ($x = 0; $x < $number; $x++) fwrite(STDOUT, "\n"); } /** * Returns user's request * * @param int $length * @return string */ private function listen($length = 1024) { return trim(fread(STDIN, $length)); } }

Скачать архивы

Сильван Работ

1470

Комментировать

rss