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 相关文章推荐
destoon二次开发模板及调用语法汇总
Jun 21 PHP
Laravel框架路由配置总结、设置技巧大全
Sep 03 PHP
php检查页面是否被百度收录
Oct 28 PHP
Symfony模板的快捷变量用法实例
Mar 17 PHP
一个简单的php路由类
May 29 PHP
PHP对称加密函数实现数据的加密解密
Oct 27 PHP
Symfony2创建基于域名的路由相关示例
Nov 14 PHP
老生常谈文本文件和二进制文件的区别
Feb 27 PHP
thinkPHP5.0框架环境变量配置方法
Mar 17 PHP
Yii2.0实现生成二维码功能实例
Oct 24 PHP
php中对象引用和复制实例分析
Aug 14 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类包含的七种语法说明
2015/06/04 PHP
PHP CURL post数据报错 failed creating formpost data
2016/10/16 PHP
浅析PHP类的反射来实现依赖注入过程
2018/02/06 PHP
PHP设计模式之建造者模式(Builder)原理与用法案例详解
2019/12/12 PHP
cnblogs TagCloud基于jquery的实现代码
2010/06/11 Javascript
js如何判断不同系统的浏览器类型
2013/10/28 Javascript
JavaScript利用append添加元素报错的解决方法
2014/07/01 Javascript
jquery表单验证插件formValidator使用方法
2016/04/01 Javascript
jQuery监听文件上传实现进度条效果的方法
2016/10/16 Javascript
Agularjs妙用双向数据绑定实现手风琴效果
2017/05/26 Javascript
JavaScript文件的同步和异步加载的实现代码
2017/08/19 Javascript
JavaScript模拟实现封装的三种方式及写法区别
2017/10/27 Javascript
Vue Cli 3项目使用融云IM实现聊天功能的方法
2019/04/19 Javascript
探索JavaScript中私有成员的相关知识
2019/06/13 Javascript
nodejs读取图片返回给浏览器显示
2019/07/25 NodeJs
vue动态循环出的多个select出现过的变为disabled(实例代码)
2019/11/10 Javascript
解决新建一个vue项目过程中遇到的问题
2020/10/22 Javascript
Python 用户登录验证的小例子
2013/03/06 Python
从零学python系列之浅谈pickle模块封装和拆封数据对象的方法
2014/05/23 Python
一个小示例告诉你Python语言的优雅之处
2014/07/04 Python
Python列表切片用法示例
2017/04/19 Python
如何高效使用Python字典的方法详解
2017/08/31 Python
python中os和sys模块的区别与常用方法总结
2017/11/14 Python
啥是佩奇?使用Python自动绘画小猪佩奇的代码实例
2019/02/20 Python
python基础 range的用法解析
2019/08/23 Python
python接口调用已训练好的caffe模型测试分类方法
2019/08/26 Python
python主线程与子线程的结束顺序实例解析
2019/12/17 Python
Python 安装 virturalenv 虚拟环境的教程详解
2020/02/21 Python
python 使用事件对象asyncio.Event来同步协程的操作
2020/05/04 Python
pytorch读取图像数据转成opencv格式实例
2020/06/02 Python
css3实现画半圆弧线的示例代码
2017/11/06 HTML / CSS
大学生简单自荐信
2013/11/10 职场文书
2014年财务人员工作总结
2014/11/11 职场文书
房产分割协议书范文
2014/11/21 职场文书
运动会100米广播稿
2015/08/19 职场文书
离婚协议书范本(2016最新版)
2016/03/18 职场文书