John Davidson

php - Calling yii2 console/controller inside frontend/controllers

0 comments
Message:


I want to be able to trigger a console controller within my frontend/controllers namespace and also be able to pass alongside some parameters so that the request runs at the background with meddling with whatever the user is doing on the frontend.


Here is my console command


<?php
namespace console\controllers;

use common\models\ApplicationStat;
use Yii;
use yii\console\Controller;
use yii\console\ExitCode;

class CronController extends Controller
{
public $ain_number;
public $din_number;
public $userId;

public function actionVerifyIdentity()
{
$model = new IdentityVerification();
$model->applicant_id = $this->userId;
$model->ain_status = $this->ain_number;
$model->din_status = $this->din_number;
$model->save();

return ExitCode::OK;

}

}

Within my frontend/controllers action, I am calling the snippet below to trigger the actionVerifyIdentity() in the console controller.


Yii::$app->runAction('cron/verify-identity', [
'din_number' => 1611515151,
'ain_number' => 118818181,
'userId' => 7893
]);

How can I achieve this as what I wrote above is showing page not found and apparently it looks as if it can only working within the console folder?



My Answer:
To call a Yii2 console controller from within your frontend/controllers namespace and pass parameters to it, you can use the following code:

php
use yii\console\Controller;
use yii\helpers\Console;

class MyController extends Controller
{
public function actionRunConsoleCommand($param1, $param2)
{
$consoleController = new \app\commands\MyConsoleController('my-console-controller', Yii::$app);
$consoleController->run('my-console-action', [$param1, $param2]);

Console::output('Console command has been triggered successfully.');
}
}


In this code snippet, we are creating a new instance of the console controller `MyConsoleController` and calling its `run` method with the desired action and parameters. You can replace `app\commands\MyConsoleController` with the actual namespace and class name of your console controller.

You can then call this action from your frontend code to trigger the console command in the background:

php
Yii::$app->runAction('my-controller/run-console-command', ['param1' => 'value1', 'param2' => 'value2']);


Make sure to adjust the namespace and class names according to your project structure.

Rate this post

3 of 5 based on 8094 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us