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中for循环语句的几种变型
Mar 16 PHP
PHP 程序授权验证开发思路
Jul 09 PHP
php设计模式 Command(命令模式)
Jun 26 PHP
关于php 接口问题(php接口主要也就是运用curl,curl函数)
Jul 01 PHP
PHP 实现判断用户是否手机访问
Jan 21 PHP
php中使用base HTTP验证的方法
Apr 20 PHP
PHP中文竖排转换实现方法
Oct 23 PHP
使用WordPress发送电子邮件的相关PHP函数用法解析
Dec 15 PHP
详解WordPress开发中过滤属性以及Sql语句的函数使用
Dec 25 PHP
php实现将数据做成json的格式给前端使用
Aug 21 PHP
PHP删除数组中指定值的元素常用方法实例分析【4种方法】
Aug 21 PHP
thinkphp5实现微信扫码支付
Dec 23 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
one.php 多项目、函数库、类库 统一为一个版本的方法
2020/08/24 PHP
JS正则中的RegExp对象对象
2012/11/07 Javascript
js关闭模态窗口刷新父页面或跳转页面
2012/12/13 Javascript
jQuery实现HTML5 placeholder效果实例
2014/12/09 Javascript
JavaScript将Web页面内容导出到Word及Excel的方法
2015/02/13 Javascript
nodejs简单实现中英文翻译
2015/05/04 NodeJs
jQuery中的deferred使用方法
2017/03/27 jQuery
详解如何在NodeJS项目中优雅的使用ES6
2017/04/22 NodeJs
详谈js对url进行编码和解码(三种方式的区别)
2017/08/16 Javascript
webpack 静态资源集中输出的方法示例
2018/11/09 Javascript
详解webpack引入第三方库的方式以及注意事项
2019/01/15 Javascript
JavaScript实现点击图片换背景
2020/11/20 Javascript
vue实现两个区域滚动条同步滚动
2020/12/13 Vue.js
Python利用Beautiful Soup模块修改内容方法示例
2017/03/27 Python
Php多进程实现代码
2018/05/07 Python
python得到电脑的开机时间方法
2018/10/15 Python
Python实现多属性排序的方法
2018/12/05 Python
wxPython电子表格功能wx.grid实例教程
2019/11/19 Python
flask 实现上传图片并缩放作为头像的例子
2020/01/09 Python
python列表切片和嵌套列表取值操作详解
2020/02/27 Python
python数据库操作mysql:pymysql、sqlalchemy常见用法详解
2020/03/30 Python
Python实现哲学家就餐问题实例代码
2020/11/09 Python
Pretty Green美国:英式摇滚服饰风格代表品牌之一
2019/01/23 全球购物
某科技软件测试面试题
2013/05/19 面试题
大学毕业登记表自我鉴定
2013/10/09 职场文书
高一自我鉴定
2013/12/17 职场文书
教师个人的自我评价分享
2014/01/02 职场文书
公交公司毕业生求职信
2014/02/15 职场文书
保密普查工作实施方案
2014/02/25 职场文书
建议书怎么写
2014/03/12 职场文书
计算机网络专业求职信
2014/06/05 职场文书
奥巴马经典演讲稿
2014/09/13 职场文书
学习党的群众路线教育实践活动心得体会范文
2014/11/03 职场文书
爱鸟护鸟的宣传语
2015/07/13 职场文书
GO语言异常处理分析 err接口及defer延迟
2022/04/14 Golang
Golang 字符串的常见操作
2022/04/19 Golang