11.用户电子报

1.建立自定义artisan命令

php artisan make:command 文件名

生成的文件会被放在app/Console/Commands/文件夹中

其中$signature为artisan命令名称,$description为命令的说明。handle()方法则是命令的工作内容。

Laraval会预设载入app/Console/Commands/文件夹下的所有命令文件

输入php artisan 会查看到所有命令。

2.除了分页paginate()外,可通过->skip()及->take()来指定略过几条数据,并取得指定条数的数据来打到分页效果。

use App\Jobs\SendMerchandiseNewsletterJob;

use App\Shop\Entity\Merchandise;

use App\Shop\Entity\User;

use DB;

use Illuminate\Console\Command;

use Log;

public function handle()

    {

        $this->info('寄送最新商品電子報(Start)');

        $this->info('撈取最新商品');

        // 撈取最新更新 10 筆可販售商品

        $total_row = 10;

        $MerchandiseCollection = Merchandise::OrderBy('created_at', 'desc')

            ->where('status', 'S')      // 可販售

            ->take($total_row)

            ->get();


        // 寄送電子信給所有會員,每次撈取 1000 筆會員資料

        $row_per_page = 1000;

        $page = 1;

        while (true) {

            // 略過資料筆數

            $skip = ($page - 1) * $row_per_page;

            // 取得分頁會員資料

            $this->comment('取得使用者資料,第 ' . $page .' 頁,每頁 ' . $row_per_page . ' 筆');

            $UserCollection = User::orderBy('id', 'asc')

                ->skip($skip)

                ->take($row_per_page)

                ->get();

            if (!$UserCollection->count()) {

                // 沒有會員資料了,停止派送電子報

                $this->question('沒有使用者資料了,停止派送電子報');

                break;

            }


            // 派送會員電子信工作

            $this->comment('派送會員電子信(Start)');

            foreach ($UserCollection as $User) {

                SendMerchandiseNewsletterJob::dispatch($User, $MerchandiseCollection)

                    ->onQueue('low');

            }

            $this->comment('派送會員電子信(End)');


            // 繼續找看看還有沒有需要寄送電子信的使用者

            $page++;

        }


        $this->info('寄送最新商品電子報(End)');

    }


3.url辅助函数中,会使用config/app.php文件中的url键值参数数据,而url键值参数会因为主机环境不同而有不同的设置。需要更改.env文件中的APP_URL的值。

4.设置任务排程。

任务排程配置文件放在app/Console/Kernel.php文件中,在schedule()方法中写入要执行的命令及执行时间。之后使用php artisan schedule:run命令才会执行。最后需要在电脑系统中每分钟都执行这个命令即可(电脑系统定时任务)。

protected function schedule(Schedule $schedule)

    {

        $schedule->command('shop:sendLatestMerchandiseNewsletter')

            ->fridays()

            ->dailyAt('18:00');

    }


5.任务排程命令信息

line()、info()、comment()、question()、error().由于信息类型不同,输入的颜色效果不同。

6.工作事项Job优先级

SendMerchandiseNewsletterJob::dispatch($User, $MerchandiseCollection) ->onQueue('high');

SendMerchandiseNewsletterJob::dispatch($User, $MerchandiseCollection) ->onQueue('low');


->onQueue定义工作事项记录位置的名称。

high和low不是优先权高低的参数,而是工作事项记录位置的名称,可以自己定义。

在命令php artisan queue:work 命令后可加入--queue的参数,然后依照优先权的高低,依次写上,并用逗号隔开。这样就会按照设置的顺序来处理工作事项。

php artisan queue:work --queue=high,low

你可能感兴趣的:(11.用户电子报)