search
HomePHP FrameworkThinkPHPGraphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

This article is written by the thinkphp framework tutorial column to introduce the use of think-queue to send emails asynchronously in user registration scenarios. I hope it will be helpful to friends in need!

Local environment:

System is: Mac Os
php version: 7.1
ThinkPHP version: 5.1.15

Recently I saw the think-queue extension class but the manual was not written. It was a headache. I found a lot of information and finally wrote a scenario. Sorry for the bad writing
First we create the project to download the tp framework and think-queue extension

Create the project:
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios
Enter the project directory to view:
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

Download the extension class
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

After downloading, enter and check:
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

Then use MAMP to create a virtual
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

Create the database and data table after the machine;

create database if not exists myproject;
use myproject;
DROP TABLE IF EXISTS member;
CREATE TABLE IF NOT EXISTS member(
  id int(11) AUTO_INCREMENT primary key comment 'ID',
  email VARCHAR(32) NOT NULL DEFAULT '' COMMENT '',
  password VARCHAR(255) NOT NULL default '' comment '',
  create_time INT(11) UNSIGNED NOT NULL DEFAULT 0 comment '',
  update_time INT(11) UNSIGNED NOT NULL DEFAULT 0 comment '',
  unique key (email)
)engine innodb charset utf8;

Start the redis service
Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

After that, some series of operations, such as opening Force routing, configure database, configure routing, configure template tags, etc....

Create page Register.php controller directory: application/index/controller/Register.php
Create Member.php model directory :application/index/model/Member.php
Create Register.php validator directory: application/index/validate/Register.php
Create the file sendActivationMail.php that processes the queue Directory: application/index/job/sendActivationMail .php

Create the operation method in the Register controller

<?php /**
 * User: 李昊天
 * Date: 18/6/7
 * Time: 上午3:15
 * Email: haotian0607@gmail.com
 */

namespace app\index\controller;

use think\Controller;
use app\index\model\Member as MemberModel;
use app\index\validate\Register as RegisterValidate;
use think\Queue;

class Register extends Controller
{
    private $model = &#39;&#39;;

    public function initialize()
    {
        $this->model = new MemberModel();
    }

    /**
     * 渲染模板 展示注册页面
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 执行注册逻辑
     */
    public function doRegister()
    {
        if ($this->request->isPost()) {
            #实例化验证器 执行验证 如果验证失败跳转并且提示
            $validate = new RegisterValidate();
            $data = $this->request->post();
            if (false === $validate->check($data)) return $this->error($validate->getError());
            //此处应该加密密码 md5 sha1 hash 都可以
            //写入注册的用户
            $result = $this->model->allowField(['email', 'password'])->save($data);
            if ($result) {
                //注册完毕后获取到邮件账号  然后加入到队列
                $this->sendActivationMail($this->model->email);
                return $this->success('注册成功,请前往邮箱激活您的账号!');
            } else {
                return $this->error('注册失败');
            }
        }
    }

    /**
     * @param string $email 邮箱账号
     */
    private function sendActivationMail($email = '')
    {
        $jobName = 'app\index\job\sendActivationMail';  //负责处理队列任务的类
        $data = ['email' => $email]; //当前任务所需的业务数据
        $jobQueueName = 'sendActivationMail'; //当前任务归属的队列名称,如果为新队列,会自动创建


        $result = Queue::push($jobName, $data, $jobQueueName);

        if ($result) {
            echo date('Y-m-d H:i:s') . '一个新的队列任务';
        } else {
            echo date('Y-m-d H:i:s') . '添加队列出错';
        }

        // php think queue:work --queue sendActivationMail --daemon
    }
}

sendActivationMail.php code

<?php /**
 * User: 李昊天
 * Date: 18/6/7
 * Time: 上午3:36
 * Email: haotian0607@gmail.com
 */

namespace app\index\job;

use think\queue\Job;
use PHPMailer\Mail;
use think\Exception;

class sendActivationMail
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        //执行发送邮件
        $isJobDone = $this->sendMail($data);

        //如果发送成功  就删除队列
        if ($isJobDone) {
            print ("<warn>任务执行成功,,已经删除!" . "</warn>\n");
            $job->delete();
        } else {
            //如果执行到这里的话 说明队列执行失败  如果失败三次就删除该任务  否则重新执行
            print ("<warn>任务执行失败!" . "</warn>\n");
            if ($job->attempts() > 3) {
                print ("<warn>删除任务!" . "</warn>\n");
                $job->delete();
            } else {

                $job->release(); //重发任务
                print ("<info>重新执行!第" . $job->attempts() . "次重新执行!</info>\n");
            }
        }
    }

    /**
     * 发送邮件
     * @param $data
     * @return bool
     */
    private function sendMail($data)
    {
        $title = '账号激活邮件';
        $msg = '欢迎您注册xxx网站,您的请点击一下连接激活您的账号!....';
        try {
            return Mail::send($title, $msg, $data['email']);
        } catch (Exception $e) {
            return false;
        }
    }
}

After writing the code, switch the controller to the current directory for execution

php think queue:work --queue sendActivationMail --daemon

Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios

There are very detailed comments in the code, but this is not complete,,, there is no error callback,
I will write the rest of the code when I have time next time!

The above is the detailed content of Graphical explanation of how to use think-queue to send emails asynchronously in user registration scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.