Hi, in this article i will show you how to run a controller yii2 via console / terminal.
I’m using linux here, if you using windows.. no problem, this is same step.
So let’s start the tutorial :
Create Controller
– First, create a controller inside console/controllers, copy script below :
(HelloController.php)
<?php namespace console\controllers; use yii\console\Controller; /** * Hello controller */ class HelloController extends Controller { public function actionIndex() { echo "Hello i'm index\n"; } public function actionUpdate() { echo "Hello i'm update\n"; } public function actionGet($name, $address) { echo "I'm " . $name . " and live in " . $address . "\n"; } public function actionArithmetic($a, $b){ $c = ($a+$b); echo "a + b = " . $c . "\n"; } }
Run The Controller Via Console
Format to run a controller via console :
php yii<controller> php yii<controller>/<function>
1) Run the controller
php yii hello
It will be execute the default function actionIndex()
2) Run the controller with specific function
php yii hello/update
3) Passing the parameter
Format to passing the parameter is :
php yii <controller>/<function> <param1> <param2>
Now try it on terminal, type :
php yii hello/get "JOHN" "Gua Tanamo"
4) Run with arithmetic
php yii hello/arithmetic 1 2
5) Working with models
a) put your model into console\models\
b) add the following script to HelloController.php :
use Yii; use app\models\Book; // call model from console\models .... public function actionShow_book(){ $model = Book::find()->all(); foreach($model as $field){ echo $field->title . "\n"; } } ....