Run controller Yii2 via console

Hi, in this article i will show you how to run a controller yii2 via console / terminal.
yii2 console
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 :


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";

console in yii2

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

command from console yii2
It will be execute the default function actionIndex()

2) Run the controller with specific function

php yii hello/update

run controller and action from console in yii2

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"

passing the parameter in console yii2

4) Run with arithmetic

php yii hello/arithmetic 1 2

run controller yii2 from console

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";

Screenshot from 2015-08-28 08:25:36

Ambar Hasbiyatmoko

Hello, I'm web developer. Passionate about programming, web server, and networking.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.