[Laravel4] 使用command执行任务

场景

  1. 比如使用redis作为计数器,然后在每天的凌晨将计数保存到MySQL
  2. 比如定时执行一些批量的任务

扩展artisan的command

例子:批量将文字题目生成为图片

artisan command:make QuestionCommand
# app/command/QuestionCommand.php

生成php文件之后,首先需要修改name为你的命令

protected $name = 'question:gen';

getArguments, getOptions 分别为获取参数和选项的值

getArguments // command arg1 arg2
getOptions // command --opt1=val1 --opt2=val2
fire // 执行命令的时候具体要做的事情

较为完整的例子

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class QuestionCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'question:gen';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成question图片';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $questions = $this->option('all') ? Question::all() : Question::whereThumb(0)->get();
        // 初始化markdown解析引擎
        $ciconia = new Ciconia\Ciconia();
        $ciconia->addExtension(new Ciconia\Extension\Gfm\FencedCodeBlockExtension());
        $ciconia->addExtension(new Ciconia\Extension\Gfm\TaskListExtension());
        $ciconia->addExtension(new Ciconia\Extension\Gfm\InlineStyleExtension());
        $ciconia->addExtension(new Ciconia\Extension\Gfm\WhiteSpaceExtension());
        $ciconia->addExtension(new Ciconia\Extension\Gfm\TableExtension());
        foreach ($questions as $question) {
            $item = array(
                'id' => $question->id,
                'absPath' => public_path('upload/question/' . $question->id . '.png'),
                'relPath' => 'question/' . $question->id . '.png',
                'question' => $ciconia->render($question->question),
            );
            Queue::push('code2png', $item, 'code2png');
            $this->info('Question ' . $question->id . ' has been added to the queue.');
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            // array('example', InputArgument::REQUIRED, 'An example argument.'),
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('all', null, InputOption::VALUE_OPTIONAL, '全部重新生成', null),
        );
    }

}

需要在app/start/artisan.php里面添加下面一行才会生效

// 4.0
$artisan->add(new QuestionCommand);
// 4.1
Artisan::add(new QuestionCommand);

命令行中这样执行

artisan question:gen --all=1

如果要在Controller里面调用,可以这样

Artisan::call('question:gen', array('--all' => 1));

标签: none

添加新评论