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
评论