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 相关文章推荐
967 个函式
Oct 09 PHP
第五章 php数组操作
Dec 30 PHP
php二维数组用键名分组相加实例函数
Nov 06 PHP
php发送post请求函数分享
Mar 06 PHP
PHP goto语句简介和使用实例
Mar 11 PHP
浅析php工厂模式
Nov 25 PHP
php实现的IMEI限制的短信验证码发送类
May 05 PHP
php解析xml方法实例详解
May 12 PHP
CI框架中redis缓存相关操作文件示例代码
May 17 PHP
PHP魔术方法之__call与__callStatic使用方法
Jul 23 PHP
PHP基于递归实现的约瑟夫环算法示例
Aug 27 PHP
PHP 观察者模式深入理解与应用分析
Sep 25 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&amp;MYSQL分页原理及实现
2007/01/02 PHP
codeigniter教程之上传视频并使用ffmpeg转flv示例
2014/02/13 PHP
PHP微框架Dispatch简介
2014/06/12 PHP
php检测apache mod_rewrite模块是否安装的方法
2015/03/14 PHP
php通过curl添加cookie伪造登陆抓取数据的方法
2016/04/02 PHP
thinkphp5框架实现数据库读取的数据转换成json格式示例
2019/10/10 PHP
漂亮的widgets,支持换肤和后期开发新皮肤(2007-4-27已更新1.7alpha)
2007/04/27 Javascript
js 图片缩放(按比例)控制代码
2009/05/27 Javascript
兼容主流浏览器的jQuery+CSS 实现遮罩层的简单代码
2014/10/14 Javascript
js QQ客服悬浮效果实现代码
2014/12/12 Javascript
Bootstrap树形组件jqTree的简单封装
2016/01/25 Javascript
【JS+CSS3】实现带预览图幻灯片效果的示例代码
2016/03/17 Javascript
Javascript es7中比较实用的两个方法示例
2017/07/21 Javascript
vue中post请求以a=a&amp;b=b 的格式写遇到的问题
2018/04/27 Javascript
详解Vue底部导航栏组件
2019/05/02 Javascript
微信小程序如何获取用户头像和昵称
2019/09/23 Javascript
[01:00:52]2018DOTA2亚洲邀请赛 4.4 淘汰赛 EG vs LGD 第一场
2018/04/05 DOTA
python获得一个月有多少天的方法
2015/06/04 Python
python网络爬虫之如何伪装逃过反爬虫程序的方法
2017/11/23 Python
python3应用windows api对后台程序窗口及桌面截图并保存的方法
2019/08/27 Python
对tensorflow中tf.nn.conv1d和layers.conv1d的区别详解
2020/02/11 Python
详解python logging日志传输
2020/07/01 Python
六种酷炫Python运行进度条效果的实现代码
2020/07/17 Python
Pycharm Plugins加载失败问题解决方案
2020/11/28 Python
HTML5自定义mp3播放器源码
2020/01/06 HTML / CSS
Burberry英国官网:英国标志性奢侈品牌
2017/03/29 全球购物
澳大利亚运动鞋零售商:The Athlete’s Foot
2018/11/04 全球购物
如何用Lucene索引数据库
2016/02/23 面试题
职业生涯规划怎么写
2013/12/29 职场文书
讲文明树新风公益广告宣传方案
2014/02/25 职场文书
《会走路的树》教后反思
2014/04/19 职场文书
办公室主任竞聘演讲稿
2014/05/15 职场文书
感恩小明星事迹材料
2014/05/23 职场文书
2014年教学管理工作总结
2014/12/02 职场文书
优秀党员先进材料
2014/12/18 职场文书
sql server偶发出现死锁的解决方法
2022/04/10 SQL Server