Create a restful application with AngularJS and Zend 2 framework (2)

#Replace the backend with Doctrine ORM

Doctrine is a very popular data access solution for PHP, it includes low level DBAL and high level OR mapping solution.

Doctrine has some Zend specific modules to support Doctrine in Zend based projects.

In this post, I will try replace the backend codes with Doctrine ORM.

Configure doctrine

Open the composer.json file, add doctrine as dependencies.

<pre> "doctrine/doctrine-orm-module":"0.*", </pre>

Update dependencies.

<pre> php composer.phar update </pre>

It could take some seconds, after it is executed successfully, there is a doctrine folder under the vendor folder.

Open config/application.config.php file, declare the DoctrineModule and DoctrineORMModule.

<pre> 'modules' => array( // 'ZendDeveloperTools', 'DoctrineModule', 'DoctrineORMModule', 'Application', 'Album' ), </pre>

Open the album module config file /modlue/Album/config/module.config.php, add the following configuration for Doctrine.

<pre> 'doctrine' => array( 'driver' => array( 'album_entities' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array(__DIR__ . '/../src/Album/Model') ), 'orm_default' => array( 'drivers' => array( 'Album\Model' => 'album_entities' ) ) ) ) </pre>

Declare the database connection in a new standalone doctrine.locale.php file.

<pre> return array( 'doctrine' => array( 'connection' => array( 'orm_default' => array( 'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver', 'params' => array( 'host' => 'localhost', 'port' => '3306', 'user' => 'root', 'password' => '', 'dbname' => 'zf2tutorial', ) ) ) ) ); </pre>

Put this file into /config/autoload folder.

Create entity class

Change the content of Album entity class to the following.

<pre> namespace Album\Model; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Album { /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** @ORM\Column(type="string") */ private $artist; /** @ORM\Column(type="string") */ private $title; public function getId() { return $this->id; } public function getArtist() { return $this->artist; } public function getTitle() { return $this->title; } public function setId($id) { $this->id = $id; } public function setArtist($artist) { $this->artist = $artist; } public function setTitle($title) { $this->title = $title; } } </pre>

The entity class is easy to be understood if you are a Java EE developer, the annotations are every similar with the JPA/Hibernate annotations.

You can use Doctrine command line tools to validate the schema declaration in the entity annotations.

<pre> vendor\bin\doctrine-module orm:validate-schema </pre>

Unlike the before Album class, Doctrine require all the properties are private or protected.

You can also use Doctrine tools to create the table from the annotations.

Remove the table album, and execute the following command.

<pre> vendor\bin\doctrine-module orm:schema-tool:create </pre>

It will generate a new fresh album table in the zf2tutorial database.

##Create controller class

Change the content of the AlbumController to the following.

<pre> &lt;?php namespace Album\Controller; use Album\Model\Album; use Zend\Mvc\Controller\AbstractRestfulController; use Zend\View\Model\JsonModel; class AlbumController extends AbstractRestfulController { public function getList() { $em = $this ->getServiceLocator() ->get('Doctrine\ORM\EntityManager'); $results= $em->createQuery('select a from Album\Model\Album as a')->getArrayResult(); return new JsonModel(array( 'data' => $results) ); } public function get($id) { $em = $this ->getServiceLocator() ->get('Doctrine\ORM\EntityManager'); $album = $em->find('Album\Model\Album', $id); // print_r($album->toArray()); // return new JsonModel(array("data" => $album->toArray())); } public function create($data) { $em = $this ->getServiceLocator() ->get('Doctrine\ORM\EntityManager'); $album = new Album(); $album->setArtist($data['artist']); $album->setTitle($data['title']); $em->persist($album); $em->flush(); return new JsonModel(array( 'data' => $album->getId(), )); } public function update($id, $data) { $em = $this ->getServiceLocator() ->get('Doctrine\ORM\EntityManager'); $album = $em->find('Album\Model\Album', $id); $album->setArtist($data['artist']); $album->setTitle($data['title']); $album = $em->merge($album); $em->flush(); return new JsonModel(array( 'data' => $album->getId(), )); } public function delete($id) { $em = $this ->getServiceLocator() ->get('Doctrine\ORM\EntityManager'); $album = $em->find('Album\Model\Album', $id); $em->remove($album); $em->flush(); return new JsonModel(array( 'data' => 'deleted', )); } } </pre>

The role of Doctrine\ORM\EntityManager is very similar with the JPA EntityManager. Doctrine\ORM\EntityManager was registered a Zend service by default, you can use it directly.

An issue I encountered is the find method returns a PHP object instead of an array, all properties of the Album object are declared as private, and return a object to client, the properties can not be serialized as JSON string.

I added a toArray method into the Album class to convert the object to an array, which overcomes this barrier temporarily.

<pre> public function toArray(){ return get_object_vars($this); } </pre>

In the AlbumController, the return statement of the get method is changed to.

<pre>return new JsonModel(array("data" => $album->toArray())); </pre>

Another issue I encountered is I have to use the FQN name(Album\Model\Album) to access the Album entity in the query.

If you find where is configured incorrectly, please let me know. Thanks.

Sample codes: https://github.com/hantsy/angularjs-zf2-sample

转载于:https://my.oschina.net/hantsy/blog/177532

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值