LoginSignup
4
2

More than 5 years have passed since last update.

CakePHP3 シェルプログラム サンプル

Last updated at Posted at 2017-09-14

仕様

下記オリジナルのシェルプログラムを作る

内容は、
①データが格納されている2つのテーブルをどれかをユーザーが選択(今回はBoards,Peopleテーブル)
②ID番号を入力してもらう。
③IDの番号のレコードを連想配列表示させる仕様

前提条件

データが格納されたBoards,People テーブルがあるとする

使用するメソッド

使用したメソッドは下記2つです。

テキストの出力

//※第二,第三引数は省略可能
$this->out(出力する値,改行の行数(デフォルトは1),レベル(Shell::QUIET,Shell::NORMAL,Shell::VERBOSE));

ユーザーからの入力を受け取る関数

$変数 = $this->in(メッセージ内容,選択する配列,デフォルト値)

サンプル

下記のコードをShellディレクトリに格納する。

UserInputShell.php
<?php
namespace App\Shell;

use Cake\Console\ConsoleOptionParser;
use Cake\Console\Shell;
use Cake\Log\Log;
use Cake\ORM\TableRegistry;

class UserInputShell extends Shell {
    public function initialize(){
        parent::initialize();
    }
    public function main() {
    //シェルを叩いたときの内容
        $this->out('以下のテーブルが利用できます');
        $this->out('[B]oards');
        $this->out('[P]eople');
       //ユーザーにどのテーブルを使用するか選択させ$tに格納
        $t = $this->in('テーブルを選択',['B','P'],'B');
        $t = strtoupper($t);
        $table = null;
        $id = $this->in('IDを入力:',null,1);
        $data = null;
        //$tの内容に応じて、switchで切り分ける
        switch($t) {
            case 'B':
                $table = 'Boards';
                $this->loadModel('Boards');
                $data = $this->Boards->get($id);
                break;
            case 'P':
                $table = 'People';
                $this->loadModel('People');
                $data = $this->People->get($id);
                break;
            default:
                $this->info("can't access Database...");
                exit();
        }
        //配列一覧を表示
        $this->out();
        $this->out("※{$table} id={$id}のレコード:");
        $this->out(print_r($data->toArray()));
    }
}

どのように表示されるか

シェルを起動させるために、CakePHPが格納されているディレクトリまでアクセス

①作成したshellプログラム(UserInputShell.php)の起動

bin/cake user_input

以下のテーブルが利用できます
[B]oards
[P]eople
テーブルを選択 (B/P)
[B] >

②Bと選択した場合

IDを入力:
[1] >

③ 1と入力したら、IDが1のレコードが連想配列で表示される

※Boards id=1のレコード:
Array
(
    [id] => 1
    [person_id] => 1
    [title] => test
    [content] => This is test
)

関数で記述した場合

リファクタリングしやすいように、関数に分けて記述すると下記のようになります。

FuncUserInputShell.php
<?php
namespace App\Shell;

use Cake\Console\ConsoleOutput;
use Cake\Console\ConsoleOptionParser;
use Cake\Console\Shell;
use Cake\Log\Log;

class FuncUserInputShell extends Shell {

    public function initialize() {
        parent::initialize();
    }

    public function main(){
        $this->out('※以下のテーブルが利用できます。');
        $this->out('[B]oards');
        $this->out('[P]eople');
        $t = $this->in('テーブルを選択:', ['B', 'P'], 'B');
        $t = strtoupper($t);
        $n = $this->in('ID番号を入力:', null, 1);
        switch($t){
            case 'B':
                $this->boards($n);
                break;
            case 'P':
                $this->people($n);
                break;
            default:
                $this->info("can't access Database...");
                exit();
        }
    }

    public function boards($id){
        $this->loadModel('Boards');
        $data = $this->Boards->get($id);
        $this->out("※Boards id={$id}");
        $this->out(print_r($data->toArray()));
    }

    public function people($id){
        $this->loadModel('People');
        $data = $this->People->get($id);
        $this->out("※People id={$id}");
        $this->out(print_r($data->toArray()));
    }

}

コマンド

先程と同じようなコマンドでも実行することができるが、下記のように記述することで、先程と同じデータを受け取ることができる

bin/cake func_user_input boards 1

→実行結果
※Boards id=1
Array
(
    [id] => 1
    [person_id] => 1
    [title] => test
    [content] => This is test
)
4
2
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
4
2