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 相关文章推荐
从一个不错的留言本弄的mysql数据库操作类
Sep 02 PHP
php下实现一个阿拉伯数字转中文数字的函数
Jul 10 PHP
PHP 字符串编码截取函数(兼容utf-8和gb2312)
May 02 PHP
用php实现的下载css文件中的图片的代码
Feb 08 PHP
批量修改RAR文件注释的php代码
Nov 20 PHP
php的闭包(Closure)匿名函数详解
Feb 22 PHP
php使用gettimeofday函数返回当前时间并存放在关联数组里
Mar 19 PHP
PHP new static 和 new self详解
Feb 19 PHP
php无限级分类实现评论及回复功能
Feb 18 PHP
PHP中上传文件打印错误错误类型分析
Apr 14 PHP
PHP实现字符串的全排列详解
Apr 24 PHP
PHP执行linux命令6个函数代码实例
Nov 24 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中10个不常见却非常有用的函数
2010/03/21 PHP
php操作JSON格式数据的实现代码
2011/12/24 PHP
php下拉选项的批量操作的实现代码
2013/10/14 PHP
PHP邮件发送类PHPMailer用法实例详解
2014/09/22 PHP
php获取目录中所有文件名及判断文件与目录的简单方法
2017/03/04 PHP
详解PHP使用Redis存储session时的一个Warning定位
2017/07/05 PHP
Yii2.0使用阿里云OSS的SDK上传图片、下载、删除图片示例
2017/09/20 PHP
javascript针对DOM的应用分析(四)
2012/04/15 Javascript
jQuery+ajax中getJSON() 用法实例
2014/12/22 Javascript
jQuery常用数据处理方法小结
2015/02/20 Javascript
javascript省市级联功能实现方法实例详解
2015/10/20 Javascript
理解javascript定时器中的setTimeout与setInterval
2016/02/23 Javascript
使用HTML5+Boostrap打造简单的音乐播放器
2016/08/05 Javascript
Chrome不支持showModalDialog模态对话框和无法返回returnValue问题的解决方法
2016/10/30 Javascript
jquery实现文字单行横移或翻转(上下、左右跳转)
2017/01/08 Javascript
JavaScript取得gridview中获取checkbox选中的值
2017/07/24 Javascript
详解Web使用webpack构建前端项目
2017/09/23 Javascript
nodejs对mongodb数据库的增加修删该查实例代码
2020/01/05 NodeJs
vue使用keep-alive实现组件切换时保存原组件数据方法
2020/10/30 Javascript
跟老齐学Python之玩转字符串(3)
2014/09/14 Python
python接口调用已训练好的caffe模型测试分类方法
2019/08/26 Python
使用Python pip怎么升级pip
2020/08/11 Python
导游的职业规划书范文
2013/12/27 职场文书
打架检讨书50字
2014/01/11 职场文书
最美乡村医生事迹材料
2014/06/02 职场文书
机械专业应届毕业生自荐书
2014/06/12 职场文书
人事行政经理岗位职责
2014/06/18 职场文书
体育运动会广播稿
2014/10/05 职场文书
社会治安综合治理责任书
2015/01/29 职场文书
英文商务邀请函范文
2015/01/31 职场文书
工作感想范文
2015/08/07 职场文书
2015年度女工工作总结
2015/10/22 职场文书
2016年大学生党员公开承诺书
2016/03/24 职场文书
redis连接被拒绝的解决方案
2021/04/12 Redis
MongoDB使用profile分析慢查询的步骤
2021/04/30 MongoDB
Java中生成微信小程序太阳码的实现方案
2022/06/01 Java/Android