LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【CakePHP3】コンソール機能shellの使い方

Posted at

以下コマンドで作成と実行が出来ます。

//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()が呼ばれる仕様となってます。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up