后臺處理數(shù)據(jù)
1.前言
前面小節(jié)介紹了如何使用 ThinkPHP
命令行快速生成指定功能的文件,本小節(jié)主要介紹如何使用 ThinkPHP
提供的自定義命令行,以后臺處理數(shù)據(jù)為例來介紹自定義命令行的用法。
2.生成自定義命令處理文件
可以使用如下的命令生成一個自定義命令行處理文件:
php think make:command Study test
如下圖所示:
Tips: 若
php
沒有加入環(huán)境變量,可以使用絕對路徑,如E:\php\php7.3.4nts\php think version
。
生成的自定義命令行文件內(nèi)容如下:
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Study extends Command
{
protected function configure()
{
// 指令配置
$this->setName('test')
->setDescription('the test command');
}
protected function execute(Input $input, Output $output)
{
// 指令輸出
$output->writeln('test');
}
}
3.配置文件加入自定義命令
打開 config\console.php
文件,加入如下內(nèi)容:
<?php
// +----------------------------------------------------------------------
// | 控制臺配置
// +----------------------------------------------------------------------
return [
// 指令定義
'commands' => [
'test' => 'app\command\Study'
],
];
如下圖所示:
4.測試自定義命令
輸入如下命令可以執(zhí)行上述自定義命令:
php think test
如下圖所示:
5.后臺處理新增數(shù)據(jù)
在上述的 execute
方法中,可以實例化一個模型類,然后循環(huán)插入數(shù)據(jù)來模擬自定義命令行來處理新增數(shù)據(jù):
protected function execute(Input $input, Output $output)
{
// 指令輸出
$names = ["趙雷","孫空","錢學(xué)","王五","張紅","李亮"];
for ($i = 0;$i < 200000;$i++){
$student = new StudentModel();
$student->name = $names[mt_rand(0,5)];
$student->age = mt_rand(18,25);
$student->id_number = "42011720040506".mt_rand(1000,9999);
$student->created_at = time();
$student->save();
}
$output->writeln('執(zhí)行完成');
}
如下圖所示:
Tips: 上圖內(nèi)容表示使用命令向?qū)W生表插入
20
萬條隨機學(xué)生數(shù)據(jù)。
再次執(zhí)行 php think test
命令之后會消耗比較長的時間,耐心等待之后數(shù)據(jù)庫數(shù)據(jù)如下圖所示:
Tips: 可以看到使用命令行后臺處理數(shù)據(jù)是不會超時停止的,這是由于使用的是 php 的
CLI
模式。
6.在控制器中使用自定義命令
這里為了演示方便,直接在 app\controller\Index
的 index
方法中,加入調(diào)用自定義命令的方法:
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Console;
class Index extends BaseController
{
public function index()
{
$output = Console::call('test');
return $output->fetch();
}
}
如下圖所示:
7.小結(jié)
本小節(jié)主要介紹了如何生成自定義命令行文件,然后配置自定義命令行,定義好自定義命令行文件之后,就可以在該文件中處理業(yè)務(wù)邏輯了,若想用 php
守護進程后臺處理數(shù)據(jù),則可以在命令行類中使用 while(1)
在后臺不斷的跑,例如使用 php
處理消息隊列訂閱的消息時可以采用這種辦法簡單的處理。
Tips: 代碼倉庫:https://gitee.com/love-for-poetry/tp6