Updated examples, added onEnter method to contexts

This commit is contained in:
Chris 2017-01-29 20:27:17 +01:00
parent ec60970b5d
commit 75c624520d
4 changed files with 47 additions and 16 deletions

View File

@ -36,9 +36,9 @@ $myShell->setPrompt("test>");
// Create an anonymous context and add a command
$ctx = $myShell->createContext("root");
$ctx->addCommand("hello", function () {
echo "Hello World!\n";
});
$ctx->addCommand("hello", function ($who="World") {
echo "Hello {$who}!\n";
}, [ "help"=>"Say hello", "args"=>"who" ]);
// Run the shell
$myShell->run();

View File

@ -6,21 +6,46 @@ use NoccyLabs\Shell\Shell;
use NoccyLabs\Shell\Context;
$shell = new Shell();
$shell->addListener("prompt", function ($event, $shell) {
$name = $shell->getContextPath();
$shell->setPrompt("shell{$name}> ");
$shell->addListener(Shell::EVT_UPDATE_PROMPT, function ($event) {
$name = $event->shell->getContextPath();
$event->shell->setPrompt("shell{$name}> ");
});
$root = new Context();
$root->addCommand("test", function () {
echo "It works!\n";
});
$root->addCommand("context", function ($name) {
$context = new Context($name);
$context->name = $name;
return $context;
});
$shell->pushContext($root);
class MyContext extends Context
{
public function __construct()
{
// Remember to call the parent constructor if you want to use
// the doccomment syntax to mark commands, as demonstrated
// at the end of this class for the bar command.
parent::__construct();
$this->addCommand("foo",[$this,"foo"],[
'help' => "Foo command"
]);
}
public function onEnter()
{
echo "Entering context!\n";
}
public function foo()
{
echo "Foo!\n";
}
/**
* @command bar
* @args
* @help Bar command
*/
public function bar()
{
echo "Bar!\n";
}
}
$shell->pushContext(new MyContext());
$shell->run();

View File

@ -66,6 +66,11 @@ class Context
$this->findCommands();
}
public function onEnter()
{
}
protected function findCommands()
{
$refl = new \ReflectionClass(get_called_class());

View File

@ -113,6 +113,7 @@ class Shell
}
$context->setShell($this);
$this->context = $context;
$context->onEnter();
$this->dispatchEvent(self::EVT_CONTEXT_CHANGED);
}