跳至主要内容

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

评论

此博客中的热门博文

Build a Reactive application with Angular 5 and Spring Boot 2.0

I have created a post to describe Reactive programming supports in Spring 5 and its subprojects, all codes of this article are updated the latest Spring 5 RELEASE, check spring-reactive-sample under my Github account.
In this post, I will create a simple blog system, including:
A user can sign in and sign out.An authenticated user can create a post.An authenticated user can update a post.Only the user who has ADMIN role can delete a post.All users(including anonymous users) can view post list and post details.An authenticated user can add his comments to a certain post. The backend will be built with the latest Spring 5 reactive stack, including:
Spring Boot 2.0, at the moment the latest version is 2.0.0.M7Spring Data MongoDB supports reactive operations for MongoDBSpring Session adds reactive support for WebSessionSpring Security 5 aligns with Spring 5 reactive stack The frontend is an Angular based SPA and it will be generated by Angular CLI.
The source code is hosted on Github, …

Activating CDI in JSF 2.3

Activating CDI in JSF 2.3 When I upgraded my Java EE 7 sample to the newest Java EE 8, the first thing confused me is the CDI beans are not recoganized in Facelects template in a JSF 2.3 based web applicaiton, which is working in the development version, but in the final release version, they are always resolved as null. I filed an issue on Mojarra and discussed it with the developers from communities and the JSF experts.
According to the content of README, In a JSF 2.3 application, to activate CDI support, declaring a 2.3 versioned faces-config.xml and adding javax.faces.ENABLE_CDI_RESOLVER_CHAIN in web.xml is not enough, you have to declare @FacesConfig annotated class to enable CDI.
Here is the steps I created a workable JSF 2.3 applicatoin in Java EE 8.
Create a Java web application, this can be done easily by NetBeans IDE, or generated by Maven archetype, for exmaple.
$ mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-we…

JSF 2.3:Websocket support

Websocket support One of the most attractive features is JSF 2.3 added native websocket support, it means you can write real-time applications with JSF and no need extra effort.
To enable websocket support, you have to add javax.faces.ENABLE_WEBSOCKET_ENDPOINT in web.xml.
<context-param> <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name> <param-value>true</param-value> </context-param> Hello Websocket Let's start with a simple example.
@ViewScoped@Named("helloBean") publicclassHelloBeanimplementsSerializable { privatestaticfinalLoggerLOG=Logger.getLogger(HelloBean.class.getName()); @Inject@PushPushContext helloChannel; String message; publicvoidsendMessage() { LOG.log(Level.INFO, "send push message"); this.sendPushMessage("hello"); } privatevoidsendPushMessage(Objectmessage) { helloChannel.send(""+ message +" at &…