>  기사  >  백엔드 개발  >  데이터베이스에 연결하기 위한 ZendFramework2의 작업에 대해

데이터베이스에 연결하기 위한 ZendFramework2의 작업에 대해

不言
不言원래의
2018-06-15 15:16:341439검색

이 글에서는 데이터베이스에 연결하기 위한 ZendFramework2의 동작을 주로 소개하며, 데이터베이스에 연결하기 위한 ZendFramework2의 구체적인 단계, 구성 방법, 관련 운영 기술 및 주의사항을 완전한 예시 형태로 분석합니다. it

이 기사의 예는 ZendFramework2가 데이터베이스에 연결하는 것에 대해 설명합니다. 참고용으로 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

zf1에 비해 zf2는 데이터베이스를 운영할 수 있게 해줍니다. 개인적인 느낌으로는 필드 별칭을 지정하는 것이 더 쉽다는 것이지만 데이터베이스 운영이 잘 구성되어 있습니다. . 기본적으로 이동할 필요는 없지만 여전히 1의 구성보다 번거롭습니다.

다시 소스 코드를 살펴보실 수 있습니다. . .

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를

Module.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=&#39;cc_user&#39;;
  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(&#39;cc_user&#39;);
      // 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(&#39;id&#39; => $id));
    $row = $rowset->current();
    if (!$row) {
      throw new \Exception("Could not find row $id");
    }
    return $row;
  }
  public function deleteStudent($id)
  {
    $this->tableGateway->delete(array(&#39;id&#39; => $id));
  }
  public function getLIValue(){
    return $this->tableGateway->getLastInsertValue();
  }
}

Student/IndexController.php입니다.

public function indexAction(){
    /* return new ViewModel(array(
      &#39;students&#39; => $this->getStudentTable()->fetchAll(), //不分页
    ));*/
    $page=$this->params(&#39;page&#39;);//走分页 在model.config.php里面设置:
/*      model.config.php      
&#39;defaults&#39; => array(
 &#39;controller&#39; => &#39;Student\Controller\Index&#39;,
 &#39;action&#39;   => &#39;index&#39;,
 &#39;page&#39;=>&#39;1&#39;,
),
*/
    $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(&#39;page&#39;, $page));
    // set the number of items per page to 10
    $paginator->setItemCountPerPage(10);
    return new ViewModel(array(
      &#39;paginator&#39; => $paginator //模板页面调用的时候的名字
    ));
  //print_r($this->getStudentTable()->fetchAll());
}

Call 템플릿 페이지에

<?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=&#39;#&#39;  class=&#39;icol-bandaid editUserInfo&#39;></a>  
      <a href=&#39;#&#39; class=&#39;icol-key changePwd&#39;></a>  
      <a herf=&#39;#&#39;  class=&#39;icol-cross deleteStud&#39;></a>
    </td>
  </tr>
<?php endforeach;?>

위 내용은 모두의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

관련 추천:
Zend Framework의 Bootstrap 클래스 사용 분석


Yii2 일반적인 데이터베이스 작업의 프레임워크 구현 분석

Zend Framework가 memcache에 저장 세션을 구현하는 방법에 대해

🎜🎜

위 내용은 데이터베이스에 연결하기 위한 ZendFramework2의 작업에 대해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.