Berikut adalah controller untuk pembuatan console pada Yii2.
class ContohController extends Controller { public $opt; public $var; public function options($actionID) { return array_merge(parent::options($actionID), [ 'opt', 'var' ]); } /** * This command echoes what you have entered as the message. * @param string $message the message to be echoed. * @return int Exit code */ public function actionIndex($message = 'hello world') { if(isset($this->opt)) echo 'Ini Option: ' . $this->opt . "\n"; if(isset($this->var)) echo 'Ini Variable: ' . $this->var . "\n"; //$name = $this->ansiFormat('Alex', Console::FG_YELLOW); echo $message . "\n"; //$this->stdout("Hello?\n", Console::BOLD); return ExitCode::OK; } }
Penggunaan console diatas adalah sebagai berikut:
- ./yii contohPerintah di atas akan menampilkan default variable $message = ‘hello world’ . Sehingga console akan memberikan return ‘hello world’
- ./yii contoh “Ini Adalah Contoh”
Perintah di atas akan mengeset default variable $message menjadi “Ini Adalah Contoh”. Sehingga console akan memberikan return “Ini Adalah Contoh” . - ./yii telegram –opt=”Ini Adalah OPT”
Perintah di atas akan mengeset option $opt menjadi “Ini Adalah OPT” dan default variable $message = ‘hello world’ juga akan dijalankan. Sehingga console akan memberikan returnIni Option: Ini Adalah OPT hello world
- ./yii telegram –var=”Ini Adalah VAR”
Perintah di atas akan mengeset option $varmenjadi “Ini Adalah VAR” dan default variable $message = ‘hello world’ juga akan dijalankan. Sehingga console akan memberikan returnIni Variable: Ini Adalah VAR hello world
Berikut beberapa tips pembuatan Console dengan option pada yii2.
mudah-mudahan dapat menjadi referensi teman-teman Yii Indonesia khususnya untuk dokumentasi penulis.
Sumber:
- https://www.yiiframework.com/doc/guide/2.0/en/tutorial-console
- https://stackoverflow.com/questions/41427048/yii2-console-command-pass-arguments-with-name