以下コマンドで作成と実行が出来ます。
//Windowsでの実行時は[/]を[\]に置き換える.
bin/cake bake shell XXX
//TestShell.phpを作る.
bin/cake bake shell Test
//shell実行
bin/cake test index
詳細は[Hello World]参照。
shell内の共通処理をタスクとして定義
多くのshell間で共通的に使われる処理は、タスクに切り出すのが推奨。
ControllerやModel同様、Taskもbakeコマンドで作成可能。
//Windowsでの実行時は[/]を[\]に置き換える.
bin/cake bake task XXX
//TestShell.phpを作る.
bin/cake bake shell util
Taskクラスは、src/Shell/Task配下に作成されます。
namespace App\Shell\Task;
use Cake\Console\Shell;
/**
* Util shell task.
*/
class UtilTask extends Shell
{
public function main()
{
// 処理
}
public function execute()
{
return "Task Called";
}
}
shell内からTask処理を呼び出してみます。
namespace App\Shell;
use Cake\Console\Shell;
/**
* Test shell command.
*/
class TestShell extends Shell
{
public $tasks = ['Util'];
public function initialize()
{
parent::initialize();
$this->loadModel('MCompanies');
}
/**
* Shell
*/
public function callAnotherShell()
{
$this->out($this->Util->execute());
}
}
publicで$tasksプロパティを定義すれば、shell内で自由に呼び出し可能。
shell内から別のshellを呼び出す
shell内から別処理、または他shellクラスを呼び出せます。
namespace App\Shell;
use Cake\Console\Shell;
use \SplFileObject;
/**
* Test shell command.
*/
class TestShell extends Shell
{
public function initialize()
{
parent::initialize();
$this->loadModel('MCompanies');
}
/**
* Hello World
*/
public function index()
{
$this->out("Hello World");
}
/**
* Shell
*/
public function callAnotherShell()
{
$this->out("start.");
$this->dispatchShell('Test', 'index');
$this->dispatchShell('Test', 'index');
$this->dispatchShell('Test', 'index');
$this->out("end.");
}
}
callAnotherShell()では、同一クラス内に定義されているindex()で呼び出し。
以下が実行結果↓
C:\xampp\htdocs\Cakephp>bin\cake test callanothershell
Welcome to CakePHP v3.3.14 Console
---------------------------------------------------------
App : src
Path: C:\xampp\htdocs\Cakephp\src\
PHP : 7.1.1
---------------------------------------------------------
start.
Hello World
Hello World
Hello World
end.
dispatchShell()の第一引数にクラス名、第二引数にメソッド名を指定。
第二引数は省略可能だが、省略するとmain()が呼ばれる仕様となってます。