跳至主要内容

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.
"doctrine/doctrine-orm-module":"0.*",
Update dependencies.
php composer.phar update
It could take some seconds, after it is executed successfully, there is adoctrine folder under the vendor folder.
Open config/application.config.php file, declare the DoctrineModuleand DoctrineORMModule.
'modules' => array(
 // 'ZendDeveloperTools',
 'DoctrineModule',
 'DoctrineORMModule',
 'Application',
 'Album'
),
Open the album module config file/modlue/Album/config/module.config.php, add the following configuration for Doctrine.
'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'
   )
     )
 )
)
Declare the database connection in a new standalonedoctrine.locale.php file.
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',
                )
            )
        )
    )
);
Put this file into /config/autoload folder.

Create entity class

Change the content of Album entity class to the following.
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;
    }

}
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.
vendor\bin\doctrine-module orm:validate-schema
Unlike the before Album class, Doctrine requires all the properties are private or protected.
You can also use Doctrine command line tools to generate the table from the annotations.
Remove the table album, and execute the following command.
vendor\bin\doctrine-module orm:schema-tool:create
It will generate a new fresh album table in the zf2tutorial database.

Create controller class

Change the content of the AlbumController to the following.
<?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',
        ));
    }

}
The role of Doctrine\ORM\EntityManager is very similar with the JPAEntityManager. 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 asprivate, 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.
public function toArray(){
 return get_object_vars($this);
}
In the AlbumController, the return statement of the get method is changed to.
return new JsonModel(array("data" => $album->toArray()));
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

Clone the sample codes from my github.com:https://github.com/hantsy/angularjs-zf2-sample
发表评论

此博客中的热门博文

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse thePostentity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute converter In this example…

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to addhibernate-enversas project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.