1. 命令行生成文件
以下命令会在 app/commands
文件夹中生成 TopicMakeExcerptCommand.php
文件
$ php artisan command:make TopicMakeExcerptCommand
Command created successfully.
2. 激活 Artisan 命令行
在 app/start/artisan.php
文件里面, 添加以下
Artisan::add(new TopicMakeExcerptCommand);
3. 加入业务逻辑代码
第一步生成的 TopicMakeExcerptCommand.php
文件, 修改以下区域
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class TopicMakeExcerptCommand extends Command {
/**
* 1. 这里是命令行调用的名字, 如这里的: `topic:excerpt`,
* 命令行调用的时候就是 `php artisan topic:excerpt`
*
* @var string
*/
protected $name = 'topic:excerpt';
/**
* 2. 这里填写命令行的描述, 当执行 `php artisan` 时
* 可以看得见.
*
* @var string
*/
protected $description = '这里修改为命令行的描述';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 3. 这里是放要执行的代码, 如在我这个例子里面,
* 生成摘要, 并保持.
*
* @return mixed
*/
public function fire()
{
$topics = Topic::all();
$transfer_count = 0;
foreach ($topics as $topic) {
if (empty($topic->excerpt))
{
$topic->excerpt = Topic::makeExcerpt($topic->body);
$topic->save();
$transfer_count++;
}
}
$this->info("Transfer old data count: " . $transfer_count);
$this->info("It's Done, have a good day.");
}}?>
4. 命令行调用
先查看下是否注册成功, 直接运行:
php artisan
开始执行命令
执行结果如下图:
$ php artisan topic:excerpt