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_SELF的安全问题
Sep 05 PHP
php面向对象 字段的声明与使用
Jun 14 PHP
PHP程序漏洞产生的原因分析与防范方法说明
Mar 06 PHP
PHP 如何获取二维数组中某个key的集合
Jun 03 PHP
php格式化电话号码的方法
Apr 24 PHP
PHP与Ajax相结合实现登录验证小Demo
Mar 16 PHP
非集成环境的php运行环境(Apache配置、Mysql)搭建安装图文教程
Apr 12 PHP
linux下php上传文件注意事项
Jun 11 PHP
PHP递归删除多维数组中的某个值
Apr 17 PHP
Yii2语言国际化自动配置详解
Aug 22 PHP
PHP实现PDO操作mysql存储过程示例
Feb 13 PHP
laravel使用redis队列实例讲解
Mar 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
我的群发邮件程序
2006/10/09 PHP
smarty的保留变量问题
2008/10/23 PHP
php 数学运算验证码实现代码
2009/10/11 PHP
PHP跳转页面的几种实现方法详解
2013/06/08 PHP
php解析xml提示Invalid byte 1 of 1-byte UTF-8 sequence错误的处理方法
2013/11/14 PHP
php判断并删除空目录及空子目录的方法
2015/02/11 PHP
PHP基于curl后台远程登录正方教务系统的方法
2016/10/14 PHP
Ajax中的JSON格式与php传输过程全面解析
2017/11/14 PHP
PJ Blog修改-禁止复制的代码和方法
2006/10/25 Javascript
js 处理URL实用技巧
2010/11/23 Javascript
JavaScript NodeTree导航栏(菜单项JSON类型/自制)
2013/02/01 Javascript
使用js获取地址栏中传递的值
2013/07/02 Javascript
JQuery调用WebServices的方法和4个实例
2014/05/06 Javascript
jquery实现鼠标滑过小图查看大图的方法
2015/07/20 Javascript
浅谈js的html元素的父节点,子节点
2016/08/06 Javascript
javascript实现的图片预览功能
2017/03/25 Javascript
nodejs 日志模块winston的使用方法
2018/05/02 NodeJs
angular4自定义表单控件[(ngModel)]的实现
2018/11/23 Javascript
详解小程序退出页面时清除定时器
2019/04/28 Javascript
javascript实现日历效果
2019/06/17 Javascript
JS实现给数组对象排序的方法分析
2019/06/24 Javascript
Vue使用Ref跨层级获取组件的步骤
2021/01/25 Vue.js
[01:15:44]首部DOTA2纪录片今日23时全网上映
2014/03/19 DOTA
通过源码分析Python中的切片赋值
2017/05/08 Python
浅谈python的深浅拷贝以及fromkeys的用法
2019/03/08 Python
Python检查图片是否损坏及图片类型是否正确过程详解
2019/09/30 Python
python程序文件扩展名知识点详解
2020/02/27 Python
Python pandas对excel的操作实现示例
2020/07/21 Python
全神贯注教学反思
2014/02/03 职场文书
2014年基建工作总结
2014/12/12 职场文书
任命通知范文
2015/04/21 职场文书
大学班长竞选稿
2015/11/20 职场文书
2016基督教会圣诞节开幕词
2016/03/04 职场文书
python中如何对多变量连续赋值
2021/06/03 Python
html+css实现滚动到元素位置显示加载动画效果
2021/08/02 HTML / CSS
Python测试框架pytest高阶用法全面详解
2022/06/01 Python