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 相关文章推荐
简单易用的计数器(数据库)
Oct 09 PHP
html中select语句读取mysql表中内容
Oct 09 PHP
PHP新手上路(十)
Oct 09 PHP
在JavaScript中调用php程序
Mar 09 PHP
php strlen mb_strlen计算中英文混排字符串长度
Jul 10 PHP
php的array_multisort()使用方法介绍
May 16 PHP
使用PHP生成PDF方法详解
Jan 23 PHP
PHP获取音频文件的相关信息
Jun 22 PHP
PHP使用PDO操作数据库的乱码问题解决方法
Apr 08 PHP
php+mysql实现的二级联动菜单效果详解
May 10 PHP
在laravel中实现ORM模型使用第二个数据库设置
Oct 24 PHP
Laravel等框架模型关联的可用性浅析
Dec 15 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 file_get_contents 函数超时的几种解决方法
2009/07/30 PHP
PHP调用Twitter的RSS的实现代码
2010/03/10 PHP
php线性表顺序存储实现代码(增删查改)
2012/02/16 PHP
PHP如何使用Memcached
2016/04/05 PHP
PHP中常用的三种设计模式详解【单例模式、工厂模式、观察者模式】
2019/06/14 PHP
PHP实现微信提现(企业付款到零钱)
2019/08/01 PHP
JS 用6N±1法求素数 实例教程
2009/10/20 Javascript
formvalidator验证插件中有关ajax验证问题
2013/01/04 Javascript
基于jquery实现后台左侧菜单点击上下滑动显示
2013/04/11 Javascript
jQuery表单获取和失去焦点输入框提示效果的实例代码
2013/08/01 Javascript
jquery easyui 结合jsp简单展现table数据示例
2014/04/18 Javascript
js动态移动滚动条至底部示例代码
2014/04/24 Javascript
jQuery实现的选择商品飞入文本框动画效果完整实例
2016/08/10 Javascript
详解JavaScript跨域总结与解决办法
2016/10/31 Javascript
layui中select,radio设置不生效的解决方法
2019/09/05 Javascript
转换layUI的数据表格中的日期格式方法
2019/09/19 Javascript
如何在JavaScript中正确处理变量
2020/12/25 Javascript
numpy中的高维数组转置实例
2018/04/17 Python
python3 pandas 读取MySQL数据和插入的实例
2018/04/20 Python
Tensorflow之Saver的用法详解
2018/04/23 Python
解决python报错MemoryError的问题
2018/06/26 Python
使用matlab或python将txt文件转为excel表格
2019/11/01 Python
Python自动发送和收取邮件的方法
2020/08/12 Python
解决Python安装cryptography报错问题
2020/09/03 Python
Python xmltodict模块安装及代码实例
2020/10/05 Python
利用纯CSS3实现动态的自行车特效源码
2017/01/20 HTML / CSS
移动端HTML5 input常见问题(小结)
2020/09/28 HTML / CSS
荷兰男士时尚网上商店:Suitable
2017/12/25 全球购物
英国内衣连锁店:Boux Avenue
2018/01/24 全球购物
Eyeko美国:屡获殊荣的睫毛膏、眼线笔和眉妆
2018/07/05 全球购物
行政助理求职自荐信
2013/10/26 职场文书
《天游峰的扫路人》教学反思
2014/04/25 职场文书
实习单位评语
2014/04/26 职场文书
员工试用期自我评价
2014/09/18 职场文书
2015年度党员个人总结
2015/02/14 职场文书
项目技术负责人岗位职责
2015/04/13 职场文书