php小脚本(2)

 http://fztree.iteye.com/blog/2211746

 在这篇文章里,我写了一个php脚本,用来定时关闭未付款的订单。

 

考虑到脚本的可扩展性

我简单封装了一个worker类

具体的执行类是CloseTradeWorker

配置文件config

日志写在/var/log/etz-dev/

 

先看配置文件

<?php

return array(

    'database'  =>  array(
                        'host' => "localhost",
                        'username' => "root",
                        'password' => "123456",
                        'database' => "etz1",
    ),

    # log 路径 #
    'log' => '/var/log/etz-dev/',

);

 

然后是CloseTradeWorker

<?php

require(dirname(__FILE__).'/../Worker.php');

class CloseTradeWorker extends Worker{

  public function exec(){
    $this->std_echo('CloseTradeWorker Start...');

    // sql
    $add_time = time() - 5*60;
    $sql = ' UPDATE etz_borrow_investor'.
           ' SET close_time = add_time + 300, status = 8'.
           ' WHERE close_time = 0 AND status = 7'.
           ' AND add_time <'.$add_time;

    // 连接数据库
    $this->init_mysql_connetion();
    // 执行sql
    $step = mysql_query($sql, $this->db_con);
    if (false === $step)
      $this->std_echo ('CloseTradeWorker Failed: '.mysql_error() );
    else
      $this->std_echo ('CloseTradeWorker Successfully executed.');
    // 关闭连接
    $this->halt_mysql_connetion();
  }

  protected function std_echo($words){
    $cfg = require(dirname(__FILE__).'/../config.php');
    $dir = $cfg['log'].'close_trade/';
    /*
     * sudo mkdir /var/log/etz-dev/close_trade
     * sudo chmod -R 777 /var/log/etz-dev/close_trade
     */
    $file = $dir.date('Y-m-d').'_close_trade.log';
    $content = date('Y-m-d H:m:s')."\t".$words."\n";
    file_put_contents($file, $content, FILE_APPEND);
    parent::std_echo($words);
  }
}

##### Worker #####
$worker = new CloseTradeWorker();
$worker->exec();
exit;

 

最后是基类

<?php

abstract class Worker{

  abstract function exec();

  ########## db访问 相关代码 ########################################################

  /* db connection */
  protected $db_con;

  protected function init_mysql_connetion(){
    $cfg = require(dirname(__FILE__).'/config.php');
    $cfg = $cfg['database'];
    $this->db_con = mysql_connect($cfg['host'],
                                  $cfg['username'],
                                  $cfg['password'] );
    if (!$this->db_con){
      $this->std_echo('Could not connect: '.mysql_error() );
      exit;
    }
    mysql_select_db($cfg['database'], $this->db_con);
  }

  protected function halt_mysql_connetion(){
    mysql_close($this->db_con);
  }

  ########################################

  protected function std_echo($words){
    echo date('Y-m-d H:m:s')."\t".$words."\n";
  }

}

 

 

终于,我觉得这样的层次能足够满足需求和未来的可扩展性了。

 

你可能感兴趣的:(PHP)