PHP 中的批处理的实现

2019-04-11 01:14:56刘景俊


这个模型首先需要 MySQL 模式。

清单 1. mailout.sql
    DROP TABLE IF EXISTS mailouts;CREATE TABLE mailouts (  id MEDIUMINT NOT NULL AUTO_INCREMENT,  from_address TEXT NOT NULL,  to_address TEXT NOT NULL,  subject TEXT NOT NULL,  content TEXT NOT NULL,  PRIMARY KEY ( id ));


这个模式非常简单。每行中有一个 from 和一个 to 地址,以及电子邮件的主题和内容。

对数据库中的 mailouts 表进行处理的是 PHP mailouts 类。

清单 2. mailouts.php
    <?phprequire_once('DB.php');class Mailouts{  public static function get_db()  {    $dsn = 'mysql://root:@localhost/mailout';    $db =& DB::Connect( $dsn, array() );    if (PEAR::isError($db)) { die($db->getMessage()); }    return $db;  }  public static function delete( $id )  {    $db = Mailouts::get_db();    $sth = $db->prepare( 'DELETE FROM mailouts WHERE id=?' );    $db->execute( $sth, $id );    return true;  }  public static function add( $from, $to, $subject, $content )  {    $db = Mailouts::get_db();    $sth = $db->prepare( 'INSERT INTO mailouts VALUES (null,?,?,?,?)' );    $db->execute( $sth, array( $from, $to, $subject, $content ) );    return true;  }  public static function get_all()  {    $db = Mailouts::get_db();    $res = $db->query( "SELECT * FROM mailouts" );    $rows = array();    while( $res->fetchInto( $row ) ) { $rows []= $row; }    return $rows;  }}?>


这个脚本包含 Pear::DB 数据库访问类。然后定义 mailouts 类,其中包含三个主要的静态函数:add、delete 和 get_all。add() 方法向队列中添加一个电子邮件,这个方法由前端使用。get_all() 方法从表中返回所有数据。delete() 方法删除一个电子邮件。

您可能会问,我为什么不只在脚本末尾调用 delete_all() 方法。不这么做有两个原因:如果在发送每个消息之后删除它,那么即使脚本在出现问题之后重新运行,消息也不可能发送两次;在批作业的启动和完成之间可能会添加新的消息。
相关文章 大家在看