как вызвать фоновую функцию из веб-контроллера в yii2

У меня есть функция контроллера, которая сохраняет некоторый файл в БД, а затем создает персональный файл PDF для каждой записи в БД и отправляет его по электронной почте. Проблема в том, что это занимает много времени. Можно ли вызвать контроллер консоли из функции веб-контроллера и передать идентификатор функции консоли? Или есть лучший или другой способ сделать это?

0

Решение

Я не думаю, что вызов консольной команды из веб-контроллера поможет слишком сильно.

Но для этого вы можете использовать, например, это расширение.

Использование:

Импортируемый класс:

use vova07\console\ConsoleRunner;
$cr = new ConsoleRunner(['file' => '@my/path/to/yii']);
$cr->run('controller/action param1 param2 ...');

Компонент приложения:

// config.php
...
components [
'consoleRunner' => [
'class' => 'vova07\console\ConsoleRunner',
'file' => '@my/path/to/yii' // or an absolute path to console file
]
]
...

// some-file.php
Yii::$app->consoleRunner->run('controller/action param1 param2 ...');

Но я рекомендую использовать рабочие очереди для этого, как RabbitMQ или же Beanstalkd, это больше подходит для вашей задачи.

1

Другие решения

Я думаю, что лучше использовать правильный класс с правильной функцией / метод, делиться этим в общей области и вызывать функцию в разных контроллерах

общая модель

    namespace common\models;

use Yii;

/**
* This is the model class for table "c2_common_user_param".
*
* @property integer $id
* @property integer $user_id
* @property string $land_scope_code
* @property string $init_lat
* @property string $init_lng
* @property integer $init_zoom
* @property string $google_maps_api_key
*
* @property DfenxUser $user
*/
class UserParam extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'c2_common_user_param';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'init_zoom'], 'integer'],
[['init_lat', 'init_lng'], 'number'],
[['land_scope_code'], 'string', 'max' => 4],
[['google_maps_api_key'], 'string', 'max' => 255]
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'user_id' => Yii::t('app', 'User ID'),
'land_scope_code' => Yii::t('app', 'Land Scope Code'),
'init_lat' => Yii::t('app', 'Init Lat'),
'init_lng' => Yii::t('app', 'Init Lng'),
'init_zoom' => Yii::t('app', 'Init Zoom'),
'google_maps_api_key' => Yii::t('app', 'Google Maps Api Key'),
];
}
}

бэкэнд-контроллер

    <?php

namespace backend\controllers;

use Yii;
use common\models\UserParam;
use common\models\UserParamSearch;

use common\models\User;

use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;


/**
* UserParamController implements the CRUD actions for UserParam model.
*/
class UserParamController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}

/**
* Lists all UserParam models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserParamSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

}

контроллер внешнего интерфейса

    <?php

namespace frontend\controllers;

use Yii;
use common\models\UserParam;
use common\models\UserParamSearch;

use common\models\User;

use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;


/**
* UserParamController implements the CRUD actions for UserParam model.
*/
class UserParamController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}

/**
* Lists all UserParam models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserParamSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

}
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector