Zend Framework 2 入门实例-Mysql数据库链接
本文在Zend Framework 2 入门实例的基础上构建
Step 1:
在全局配置文件中配置数据库链接信息,以及ZF2的数据库适配器
( path: /config/autoload/global.php )
return array( 'db' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=YOUR DBNAME HERE;host=localhost', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' ), ), //数据库适配器 'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', ), ), );
Step 2:
配置数据库访问帐号和密码
建立文件config/autoload/local.php,并填写数据库用户名以及密码
array( 'username' => 'YOUR USERNAME HERE', 'password' => 'YOUR PASSWORD HERE', ), );
Step 3.1:
此时就可以访问数据库并进行操作了
本演示和官方手册一样试用TableGatway来进行数据库操作
在此之前我在数据库中建立了一张用户表用于演示
id | name |
1 | Admin |
Step 3.2:
建立文件User.php ( path: /module/Helloword/src/Helloword/Model/User.php)
<?php namespace Helloword\Model; class User { public $id; public $name; public function exchangeArray($d) { $this->id = (isset($d['id'])) ? $d['id'] : null; $this->name = (isset($d['name'])) ? $d['name'] : null; } }
建立文件UserTable.php ( path: /module/Helloword/src/Helloword/Model/UserTable.php)
<?php namespace Helloword\Model; use Zend\Db\TableGateway\TableGateway; class UserTable { protected $tableGatewat; public function __construct(TableGateway $tableGatewat) { $this->tableGatewat = $tableGatewat; } /** * 根据传入的id获取用户信息 * * @param int $id 用户id */ public function getUser($id) { try { return $this->tableGatewat->select(array('id' => $id)); } catch (\Exception $e) { } } }
Step 3.3
接下来我们就可以通过上面的类获取用户信息了,在zf2中,为我们提供了更方面的调用类的方式
在Module.php ( path: /Module/Helloword/Module.php )中添加:
<?php namespace Helloword; use Zend\Db\ResultSet\ResultSet; use Zend\Db\TableGateway\TableGateway; use Helloword\Model\User; use Helloword\Model\UserTable; class Module { ... public function getServiceConfig() { return array( 'factories' => array( 'Helloword\Model\UserTable' => function($sm) { $tableGateway = $sm->get('UserTableGateway'); $table = new UserTable($tableGateway); return $table; }, 'UserTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new User()); return new TableGateway('user', $dbAdapter, null, $resultSetPrototype); }, ) ) } }
接下来就可以在控制器中用ZF2的Services来调用UserTable类了
<?php namespace Helloword\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class HellowordController extends AbstractActionController { protected $userTable; public function indexAction() { $resSelectUser = $this->getUserTable()->getUser(1); $resCurrent = $resSelectUser->current(); return new ViewModel(array('hello' => 'hi'.$resCurrent->name)); } public function getUserTabel() { if (!$this->userTable) { $sm = $this->getServiceLocator() $this->userTable = $sm->get('Helloword\Model\UserTable'); } return $this->userTable; } }