ZendFramework2 connects to the database operation instance and zendframework2 instance

Source: Internet
Author: User
Tags php foreach

ZendFramework2 connects to the database operation instance and zendframework2 instance

This example describes how to connect ZendFramework2 to a database. We will share this with you for your reference. The details are as follows:

Compared with zf1, zf2 makes it easy to create aliases for fields for database operations, however, although you do not need to perform operations on the database After configuring the database, it is still more complicated than the configuration of 1,

Let's look at the source code...

Add 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. This is Model/Student. php.

Namespace Student \ Model; class Student {public $ id; public $ name; public $ phone; public $ mark; public $ email; public function exchangeArray ($ data) // alias {$ 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

<? Phpnamespace Student \ Model; use Zend \ Db \ ResultSet; use Zend \ Db \ TableGateway; use Zend \ Db \ SQL \ Select; use Zend \ Paginator \ Adapter \ DbSelect; use Zend \ Paginator; class StudentTable {protected $ tableGateway; protected $ table = 'CC _ user '; public function _ construct (TableGateway $ tableGateway) {$ this-> tableGateway = $ tableGateway;} public function fetchAll ($ paginated) {// paging 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 agains T $ 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 ("cocould 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 call Database

Public function indexAction () {/* return new ViewModel (array ('students' => $ this-> getStudentTable ()-> fetchAll (), // No paging )); */$ page = $ this-> params ('page'); // go through the page in the model. config. php settings:/* 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 // name of the template page when calling); // print_r ($ this-> getStudentTable () -> fetchAll ());}

Call on the template page

<? Php foreach ($ this-> paginator as $ student):?> <Tr id = "<? Php echo $ this-> escapeHtml ($ student-> id);?> "> <Td> <? Php echo $ this-> escapeHtml ($ student-> id);?> </Td> <? Php echo $ this-> escapeHtml ($ student-> name);?> </Td> <? Php echo $ this-> escapeHtml ($ student-> phone);?> </Td> <? Php echo $ this-> escapeHtml ($ student-> email);?> </Td> // apply the alias in Student. php <td> <? Php echo $ this-> escapeHtml ($ student-> mark);?> </Td> <a href = '#' class = 'iconcol-bandaid edituserinfo'> </a> <a href = '# 'class = 'iconcol-key changePwd '> </a> <a herf =' # 'class = 'icol-cross deleteStud'> </a> </td> </tr> <? Php endforeach;?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.