ZendFrame实现一个投票模块

来源:互联网 发布:c语言运算符结合方向 编辑:程序博客网 时间:2024/04/28 09:49

思路分析:获取用户ip,判断该ip 是否被禁用,然后判断今天有没有投了 再做出相应的操作...

主要步骤如下:

配置一下application.ini 让项目可以连接到指定的数据库

[mysql]
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.username = root
db.params.password =
db.params.dbname=votedb


初始化数据库适配器

<?php
 // 做一个父类,专门供其它控制器来继承的
 class BaseController extends Zend_Controller_Action{
  public function init(){
  //初始化数据库适配器
  $url = constant("APPLICATION_PATH").DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'application.ini';
  $dbconfig = new Zend_Config_Ini($url,"mysql");
  $db = Zend_Db::factory($dbconfig->db);
  Zend_Db_Table::setDefaultAdapter($db);
  }
 }


//创建表模型

<?php
//这里一定要继承Zend_db_Table,否则就不是表模型
 class Item extends Zend_Db_Table{
  protected $_name = 'item';
 }

//投票控制器

<?php
require_once 'BaseController.php';
require_once APPLICATION_PATH.'/models/Item.php';
require_once APPLICATION_PATH.'/models/Filter.php';
require_once APPLICATION_PATH.'/models/VoteLog.php';


class VoteController extends BaseController{
public function voteAction(){

$item_id = $this->getRequest()->getParam('itemid','no');  //获取id
//用于获取ip 地址$_SERVER['REMOTE_ADDR']
  $ip = $this->getRequest()->getServer('REMOTE_ADDR');
  //看看这个ip是否被禁用
  $filterModel = new Filter();
  $filters =  $filterModel->fetchAll("ip='$ip'")->toArray();
  if(count($filters)>=1){
  $this->view->info="你被警用了!";
  //成功,跳转到一个全局的视图
  $this->_forward('err','global');
  return;
  }
 
//先看voteLOg 这个表今天有没有透过一次
$today=date('Ymd');//今天的时间
$voteLogModel = new VoteLog();
$where = "ip='$ip' AND vote_date=$today";
$res = $voteLogModel->fetchAll($where)->toArray();
if(count($res)>0){  //如果大于0表示已经投 了
$this->render('error');
return ;
}else{
//更新item的vote_count,添加更新日志
$data = array(
'ip' => $ip,
'vote_date'=>$today,
'item_id'=>$item_id
);
if($voteLogModel->insert($data)>0){  //如果更新成功要更改item 表
$itemModel = new Item();
//通过主键直接获取对应的item
$item = $itemModel->find($item_id)->toArray();

$newvote = $item[0]['vote_count']+1;
$set = array(
'vote_count'=>$newvote
);
$where = "id=$item_id";
$itemModel->update($set, $where);
}
$this->render('ok');
}
}
}


?>


原创粉丝点击