ZendFramework2连接数据库操作实例


Posted in PHP onApril 18, 2017

本文实例讲述了ZendFramework2连接数据库操作。分享给大家供大家参考,具体如下:

相对于zf1,来说,zf2让我们对于数据库这方面的操作我的个人感觉是对于字段起别名简单了,但是对数据库的操作虽然配置写好的就基本不需要动了,但是还是比1的配置要繁琐,

还是那句话,大家可以去看看源码。。。

Module.php 里面添加

public function getServiceConfig()
{
    return array(
      'factories' => array(
        'Student\Model\StudentTable' => function($sm) {
          $tableGateway = $sm->get('StudentTableGateway');
          $table = new StudentTable($tableGateway);
          return $table;
        },
        'StudentTableGateway' => function ($sm) {
          $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
          $resultSetPrototype = new ResultSet();
          $resultSetPrototype->setArrayObjectPrototype(new Student());
          return new TableGateway('cc_user', $dbAdapter, null, $resultSetPrototype);//table Name is cc_user
        },
      ),
    );
}

student.php 这个是Model/Student.php

namespace Student\Model;
class Student
{
  public $id;
  public $name;
  public $phone;
  public $mark;
  public $email;
  public function exchangeArray($data)//别名
  {
    $this->id   = (!empty($data['cc_u_id'])) ? $data['cc_u_id'] : null;
    $this->name = (!empty($data['cc_u_name'])) ? $data['cc_u_name'] : null;
    $this->phone = (!empty($data['cc_u_phone'])) ? $data['cc_u_phone'] : null;
    $this->mark = (!empty($data['cc_u_mark'])) ? $data['cc_u_mark'] : null;
    $this->email = (!empty($data['cc_u_email'])) ? $data['cc_u_email'] : null;
  }
}

StudentTable.php Model/StudentTable.php

<?php
namespace Student\Model;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
class StudentTable
{
  protected $tableGateway;
  protected $table='cc_user';
  public function __construct(TableGateway $tableGateway)
  {
    $this->tableGateway = $tableGateway;
  }
  public function fetchAll($paginated)
  {//分页
     if($paginated) {
      // create a new Select object for the table album
      $select = new Select('cc_user');
      // create a new result set based on the Student entity
      $resultSetPrototype = new ResultSet();
      $resultSetPrototype->setArrayObjectPrototype(new Student());
      // create a new pagination adapter object
      $paginatorAdapter = new DbSelect(
        // our configured select object
        $select,
        // the adapter to run it against
        $this->tableGateway->getAdapter(),
        // the result set to hydrate
        $resultSetPrototype
      );
      $paginator = new Paginator($paginatorAdapter);
      return $paginator;
    }
    $resultSet = $this->tableGateway->select();
    return $resultSet;
  }
  public function getStudent($id)
  {
    $id = (int) $id;
    $rowset = $this->tableGateway->select(array('id' => $id));
    $row = $rowset->current();
    if (!$row) {
      throw new \Exception("Could not find row $id");
    }
    return $row;
  }
  public function deleteStudent($id)
  {
    $this->tableGateway->delete(array('id' => $id));
  }
  public function getLIValue(){
    return $this->tableGateway->getLastInsertValue();
  }
}

Student/IndexController.php 调用数据库

public function indexAction(){
    /* return new ViewModel(array(
      'students' => $this->getStudentTable()->fetchAll(), //不分页
    ));*/
    $page=$this->params('page');//走分页 在model.config.php里面设置:
/*model.config.php
'defaults' => array(
 'controller' => 'Student\Controller\Index',
 'action'   => 'index',
 'page'=>'1',
),
*/
    $paginator = $this->getStudentTable()->fetchAll(true);
    // set the current page to what has been passed in query string, or to 1 if none set
    $paginator->setCurrentPageNumber((int)$this->params()->fromQuery('page', $page));
    // set the number of items per page to 10
    $paginator->setItemCountPerPage(10);
    return new ViewModel(array(
      'paginator' => $paginator //模板页面调用的时候的名字
    ));
  //print_r($this->getStudentTable()->fetchAll());
}

在模板页面的调用

<?php foreach ($this->paginator as $student) : ?>
<tr id="<?php echo $this->escapeHtml($student->id);?>">
  <td><?php echo $this->escapeHtml($student->id);?></td>
  <td><?php echo $this->escapeHtml($student->name);?></td>
  <td><?php echo $this->escapeHtml($student->phone);?></td>
  <td><?php echo $this->escapeHtml($student->email);?></td>//应用了在Student.php的别名
  <td><?php echo $this->escapeHtml($student->mark);?></td>
    <td><a href='#'  class='icol-bandaid editUserInfo'></a>  
      <a href='#' class='icol-key changePwd'></a>  
      <a herf='#'  class='icol-cross deleteStud'></a>
    </td>
  </tr>
<?php endforeach;?>

希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。

PHP 相关文章推荐
PHP截取汉字乱码问题解决方法mb_substr函数的应用
Mar 30 PHP
php和js如何通过json互相传递数据相关问题探讨
Feb 26 PHP
关于PHP结束标签的使用细节探讨及联想
Mar 04 PHP
PHP图片等比例缩放生成缩略图函数分享
Jun 10 PHP
php获取指定日期之间的各个周和月的起止时间
Nov 24 PHP
PHP基于phpqrcode生成带LOGO图像的二维码实例
Jul 10 PHP
ThinkPHP实现图片上传操作的方法详解
May 08 PHP
PDO::quote讲解
Jan 29 PHP
详解PHP多个进程配合redis的有序集合实现大文件去重
Mar 06 PHP
解决Laravel blade模板转义html标签的问题
Sep 03 PHP
Yii框架 session 数据库存储操作方法示例
Nov 18 PHP
PHP 对接美团大众点评团购券(门票)的开发步骤
Apr 03 PHP
PHP实现的数独求解问题示例
Apr 18 #PHP
PHP使用finfo_file()函数检测上传图片类型的实现方法
Apr 18 #PHP
php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】
Apr 18 #PHP
基于thinkPHP3.2实现微信接入及查询token值的方法
Apr 18 #PHP
PHP递归删除多维数组中的某个值
Apr 17 #PHP
Thinkphp5.0自动生成模块及目录的方法详解
Apr 17 #PHP
php正则表达式基本知识与应用详解【经典教程】
Apr 17 #PHP
You might like
PHP命令空间namespace及use的用法小结
2017/11/27 PHP
jQuery判断密码强度实现思路及代码
2013/04/24 Javascript
ajax请求get与post的区别总结
2013/11/04 Javascript
调用HttpHanlder的几种返回方式小结
2013/12/20 Javascript
jQuery使用empty()方法删除元素及其所有子元素的方法
2015/03/26 Javascript
jQuery实现两款有动画功能的导航菜单代码
2015/09/16 Javascript
AngularJS入门教程之AngularJS 模板
2016/08/18 Javascript
[Bootstrap-插件使用]Jcrop+fileinput组合实现头像上传功能实例代码
2016/12/20 Javascript
jQuery加载及解析XML文件的方法实例分析
2017/01/22 Javascript
微信小程序 向左滑动删除功能的实现
2017/03/10 Javascript
windows下vue.js开发环境搭建教程
2017/03/20 Javascript
浅析JS中的 map, filter, some, every, forEach, for in, for of 用法总结
2017/03/29 Javascript
JQuery实现定时刷新功能代码
2017/05/09 jQuery
VUE 使用中踩过的坑
2018/02/08 Javascript
Vue基本使用之对象提供的属性功能
2019/04/30 Javascript
layui树形菜单动态遍历的例子
2019/09/23 Javascript
[59:08]Ti4 冒泡赛第二天 NEWBEE vs Titan 2
2014/07/15 DOTA
21行Python代码实现拼写检查器
2016/01/25 Python
Python 实现 贪吃蛇大作战 代码分享
2016/09/07 Python
Python进阶_关于命名空间与作用域(详解)
2017/05/29 Python
Pyinstaller将py打包成exe的实例
2018/03/31 Python
DES加密解密算法之python实现版(图文并茂)
2018/12/06 Python
使用Python制作简单的小程序IP查看器功能
2019/04/16 Python
python-numpy-指数分布实例详解
2019/12/07 Python
使用 Python 写一个简易的抽奖程序
2019/12/08 Python
VSCode基础使用与VSCode调试python程序入门的图文教程
2020/03/30 Python
python 决策树算法的实现
2020/10/09 Python
如何用 Python 处理不平衡数据集
2021/01/04 Python
英国Office鞋店德国网站:在线购买鞋子、靴子和运动鞋
2018/12/19 全球购物
New Balance比利时官方网站:购买鞋子和服装
2021/01/15 全球购物
材料成型专业个人求职信范文
2013/09/25 职场文书
银行财务部实习生的自我鉴定
2013/11/27 职场文书
幼儿园家长评语
2014/02/10 职场文书
文明寝室申报材料
2014/05/12 职场文书
扬尘污染防治方案
2014/06/15 职场文书
法制主题班会教案
2015/08/13 职场文书