Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Generate Doctrine Entities from Existing Database using DoctrineModule and DoctrineORMModule

Posted in orm, Teknologi, Tutorial PHP, Zend Framework 2 by samsonasik on April 10, 2013

zf2-zendframework2If we are working with Doctrine , we usually create entities first, and generate the database tables. How if the situation is the database tables and data is already ready, and we have to create an application based on doctrine and Zend Framework 2? We need generate entities! Don’t create them manually!
For example, i have two tables : album and track (i’m using PostgreSQL ) like the following :

-- Table: album
  id bigserial NOT NULL,
  artist character varying(255),
  title character varying(255),
  OWNER TO developer;

-- Table: track
  track_id bigserial NOT NULL,
  track_title character varying(255),
  album_id bigint,
  CONSTRAINT track_pkey PRIMARY KEY (track_id ),
  CONSTRAINT fk_track_album FOREIGN KEY (album_id)
  OWNER TO developer;

Ok, let’s create an application based on ZF2 step by step :
1. install ZF2 SkeletonApplication

git clone git://github.com/zendframework/ZendSkeletonApplication.git zftutordoctrine

2. add “doctrine/doctrine-orm-module” to your zftutordoctrine/composer.json

    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": ">2.1.3",
        "doctrine/doctrine-orm-module": "0.*"

3. Install it

php composer.phar self-update && php composer.phar install

4. Create an Album module with structure entity like the following :
5. Configure doctrine connection
You can define it at one file, but separate it with two file(local and global) can make security happy :D
a. config/autoload/doctrine.global.php

return array(
    'doctrine' => array(
        'connection' => array(
            'orm_default' => array(
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                    'params' => array(
                        'host' => 'localhost',
                        'port' => '5432',
                        'dbname' => 'zftutordoctrine',

b. config/autoload/doctrine.local.php

return array(
    'doctrine' => array(
        'connection' => array(
            'orm_default' => array(
                'driverClass' => 'Doctrine\DBAL\Driver\PDOPgSql\Driver',
                    'params' => array(
                        'user' => 'developer',
                        'password' => '123456',

6. register Album\Entity into doctrine driver in module/Album/config/module.config.php

return array(
    'doctrine' => array(
        'driver' => array(
            'Album_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(__DIR__ . '/../src/Album/Entity')
            'orm_default' => array(
                'drivers' => array(
                     'Album\Entity' =>  'Album_driver'

7. Register modules into config/application.config.php

return array(
    'modules' => array(
    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => array(
        'module_paths' => array(
        'config_glob_paths' => array(

8. Generate Time !
a. convert-mapping

./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping --namespace="Album\\Entity\\" --force  --from-database annotation ./module/Album/src/

it will export “annotation” mapping information into ./module/Album/src/
b. generate-entities

 ./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ --generate-annotations=true

it will add setter/getter into entities.
and you will get the following entities AUTOMATICALLY :


namespace Album\Entity;

use Doctrine\ORM\Mapping as ORM;

 * Album
 * @ORM\Table(name="album")
 * @ORM\Entity
class Album
     * @var integer
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="album_id_seq", allocationSize=1, initialValue=1)
    private $id;

     * @var string
     * @ORM\Column(name="artist", type="string", length=255, nullable=true)
    private $artist;

     * @var string
     * @ORM\Column(name="title", type="string", length=255, nullable=true)
    private $title;

     * Get id
     * @return integer 
    public function getId()
        return $this->id;

     * Set artist
     * @param string $artist
     * @return Album
    public function setArtist($artist)
        $this->artist = $artist;
        return $this;

     * Get artist
     * @return string 
    public function getArtist()
        return $this->artist;

     * Set title
     * @param string $title
     * @return Album
    public function setTitle($title)
        $this->title = $title;
        return $this;

     * Get title
     * @return string 
    public function getTitle()
        return $this->title;



namespace Album\Entity;

use Doctrine\ORM\Mapping as ORM;

 * Track
 * @ORM\Table(name="track")
 * @ORM\Entity
class Track
     * @var integer
     * @ORM\Column(name="track_id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="track_track_id_seq", allocationSize=1, initialValue=1)
    private $trackId;

     * @var string
     * @ORM\Column(name="track_title", type="string", length=255, nullable=true)
    private $trackTitle;

     * @var \Album\Entity\Album
     * @ORM\ManyToOne(targetEntity="Album\Entity\Album")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="album_id", referencedColumnName="id")
     * })
    private $album;

     * Get trackId
     * @return integer 
    public function getTrackId()
        return $this->trackId;

     * Set trackTitle
     * @param string $trackTitle
     * @return Track
    public function setTrackTitle($trackTitle)
        $this->trackTitle = $trackTitle;
        return $this;

     * Get trackTitle
     * @return string 
    public function getTrackTitle()
        return $this->trackTitle;

     * Set album
     * @param \Album\Entity\Album $album
     * @return Track
    public function setAlbum(\Album\Entity\Album $album = null)
        $this->album = $album;
        return $this;

     * Get album
     * @return \Album\Entity\Album 
    public function getAlbum()
        return $this->album;

9. Fill database tables rows, and Let’s call from whatever controller for testing :

    public function indexAction()
        $em = $this->getServiceLocator()
        $data = $em->getRepository('Album\Entity\Track')->findAll();
        foreach($data as $key=>$row)
            echo $row->getAlbum()->getArtist().' :: '.$row->getTrackTitle();
            echo '<br />';

References :
1. Conversation with Anass Ans
1. http://docs.doctrine-project.org/en/2.0.x/reference/tools.html
2. http://wildlyinaccurate.com/useful-doctrine-2-console-commands

About these ads

70 Responses

Subscribe to comments with RSS.

  1. Mohammad Nomaan Patel said, on April 11, 2013 at 5:03 pm

    Thanks Samsonasik!!!

    Was eagerly waiting for this post and it worked perfectly..

    Keep posting this kind of stuff in future


  2. tawfek daghistani said, on April 12, 2013 at 4:28 pm

    HI ,
    i guess I have a simpler implementations , I wanted to share you
    check out this gist : https://gist.github.com/tawfekov/4079388

    just copy & change database config , and run it via cli , the only manual thing you need to is writing your own namespace

  3. Mohammad Nomaan Patel said, on April 12, 2013 at 6:09 pm

    I want to ask if there is a way to generate entities for a specific table of a database. eg. I want to generate entities for state table from db with also contains other more tables such as company, users,etc


  4. Khiem said, on April 14, 2013 at 7:08 pm

    Hi samsonasik,

    Sorry for my question that is not in this topic.

    I would like to display a view from an action of a specific controller in another view of an action of a controller or layout in ZF2. In ZF1, we have $this->action plugin in view. Is there something similar in ZF2?

    Thank you very much!

    • samsonasik said, on April 14, 2013 at 8:00 pm

      you can replace it by $this->render. for example :

        echo $this->render('application/index/test', array('var' => 'value')); 

      and in another view : ( application/index/test.phtml ) you can call the var

      echo $var; 
      • Khiem said, on April 14, 2013 at 9:28 pm

        The string ‘application/index/test’ is the template file? PhpRenderer automatically resolve it to test.phtml in view directory?
        Thank you!

      • samsonasik said, on April 14, 2013 at 11:39 pm


  5. Qubess Ali said, on April 18, 2013 at 8:59 pm

    HI, I am working on zf2 and doctrine. And my DB is Oracle. Now when I am trying to generate the entities, it giving me error as “Table ACCOUNTS has no primary key. Doctrine does not support reverse engineering from tables that don’t have a primary key.”. So now my question is that whether is it possible to generate entities for table who doesn’t have primary key?

    • samsonasik said, on April 19, 2013 at 5:35 am

      i have no idea, but i think primary key is what you must have when define a table.

  6. Thomas Sens said, on April 20, 2013 at 3:58 am

    can you create a class that extends the entity, where can I create new methods to be able to call on different controllers? because I do not want to duplicate code.
    “AlbumGateway extends Entity Album”
    implements an automatically:
    – GetRepository (‘Album\Entity\Album’)
    – GetServiceLocator()->get(‘doctrine.entitymanager.orm_default’)

    in a controller:
    $album = new AlbumGateway ();
    $return = $album->getSomething(“some_param”);

    I think this way would be simpler and faster to development
    I’ve been trying to implement this but I did not succeed, lack of knowledge
    what do you think?

  7. Angus said, on April 25, 2013 at 4:52 pm


    i’m having trouble using this cmd with windows :
    /vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Album/src/ –generate-annotations=true

    i replace Album by my own module but still not works cause it’s not an internal or external cmd or exe file :x

    • samsonasik said, on April 25, 2013 at 6:25 pm

      for note, “/vendor” as your type should be “./vendor” with adding “.” as prefix. if you’re using windows powershell, it should be work.
      other way, try to change “/” (slash) with “\” (backslash), absolute path is better.

  8. […] 装好Doctrine之后,可以自动生成Entity,tutorial: E:zf_workplaceintranet>php /zf_workplace/intranet/vendor/doctrine/doctrine-module/bin/doctrine-module.php orm:convert-mapping –namespace=”Album\Entity\” –force  –from-database annotation ./module/Album/src/ […]

  9. Vitor said, on June 18, 2013 at 11:35 pm

    Great, but how can we make a crud with this relation?

    For example how to populate a combobox with categories and to save for some product?

    Can you make an example?

    Thank you.

  10. Amit Dangwal said, on July 10, 2013 at 10:53 pm

    Thanks samsonasik. It is very simple and very useful tutorial. Only 1 change I have to made during execution(as I was getting exception (Parse error: syntax error, unexpected T_NS_SEPARATOR, expecting T_STRING)

    original line:
    ./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=”Album\\Entity\\” –force –from-database annotation ./module/Album/src/

    modified line:
    ./vendor/doctrine/doctrine-module/bin/doctrine-module orm:convert-mapping –namespace=Album\Entity\ –force –from-database annotation ./module/Album/src/

    Amit Dangwal

  11. Thomas Dutrion said, on July 12, 2013 at 1:44 am


    Thanks for this very good tutorial.

    I wondered how to extend generated entities, in order to be still able to regenerate at any time.

    Simple example: on a User class, you have for instance firstname and lastname, and you need a new method such as getFullName() { return $this->firstname.’ ‘.$this->lastname; }

    If you put this method in your entity, you will erase it the next time you want to generate entities. If you extends User, in ExtendedUser for example, you won’t be able to find your ExtendedUser using the Entity Manager.

    What would you recommend?


    • samsonasik said, on July 13, 2013 at 12:44 am

      I recommend to generate if just necessary :). Typing is good :)

  12. Johan said, on July 19, 2013 at 11:54 pm

    what if you have different modules and you need to generate some entities for one module, other entities for another module, and so on?

    • samsonasik said, on July 20, 2013 at 12:33 am

      for some table, try –filter=”Yourtablename” , I have no idea for filtering complex like that, maybe create your own script to get it done ;)

  13. Ahmed said, on August 6, 2013 at 4:45 pm

    I have this error when convert-mapping
    PHP Fatal error: Uncaught exception ‘RuntimeException’ with message ‘Options with name “Caisse_driver” could not be found in “doctrine.driver”.’ in /home/ahmed/Desktop/test/vendor/doctrine/doctrine-module/src/DoctrineModule/Service/AbstractFactory.php:81

  14. Ragunathan said, on August 29, 2013 at 5:53 pm

    I Want Search the table data in webpage…?? i want to implement the search field in my project ..i download doctrinesearch using this url..

  15. wodaxia said, on August 30, 2013 at 4:51 pm

    Thanks for sharing this code. It is very useful..
    I have a similiar scenario as yours but have some issues in adding a tracker. I have two many-to-one releationship entities: Album(1) and Tracker(m).

    My code is like this:
    $tracker = new Tracker();
    $tracker->album = constrcuctAlbumfromDB();

    This would result error:
    ‘ that was not configured to cascade persist operations for entity: \album@00000000349002ee00000000c955fd11. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={“persist”}). If you cannot find out which entity causes the problem implement ‘Album#__toString()’ to get a clue.

    After I add cascade={“persist”} for $album in tracker, The error disappear, but the problem is a new tracker is insert each time i added a tracker. THis is not expected.. What I want is only to insert a tracker, album_id of it points to existing album record..

    Thanks for help.

  16. Jazz said, on September 8, 2013 at 9:01 am

    Hi everybody,

    I followed all step; but have an issues on orm:generate-entities with message:
    No Metadata Classes to process.

    orm:convert-mapping wokrs fine, and files create on Entity folder.

    Have you idea ?

    Thanks very much

  17. Bharath said, on September 11, 2013 at 8:31 pm

    I have a one form and i have two entity..if i pass one form value that will stored in two tables(entity)..can u help me..

  18. Bharath said, on September 11, 2013 at 9:30 pm

    I have two tables like role,rolerights i want to add the data in both table in single form i have one controller, one PHTML(add.phtm),two entity(role,rolerights),one form(role),,where i write the query ??

  19. Thomas D said, on October 8, 2013 at 8:58 pm

    Good Job! Tanks a lot!

  20. Peter said, on October 22, 2013 at 1:32 pm

    I get this error…
    Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\ServiceNotFoundException’ with message ‘Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.cli’ in /Users/bla/Sites/bla/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:495

    Thanks in advance!

    • Daniela said, on October 28, 2013 at 8:12 pm

      Peter did you found a solution? I have the same issue!

  21. web2sign said, on November 19, 2013 at 9:08 am

    HI I have a problem…. i’ve follow all the instructions but in generate time i got an error

    I’ve entered this in command
    doctrine-module orm:convert-mapping –namespace=”Album\\Entity\\” –force –from-database annotation ./module/Album/src/

    and I got an error
    could not find driver

    Was is because I dont have the track table?
    The files I have is from the skeleton from zend, it has already the album add edit delete tutorial,
    and I want to switch it to doctrine orm instead of zend db….

    • Edan Schwartz said, on July 26, 2014 at 12:25 am

      Are you using PostgreSQL? If not, you’ll need to tweak the configuration a bit.

      I was using MySQL, so my config ended up looking like this:

      ‘doctrine’ => array(
      ‘connection’ => array(
      ‘orm_default’ => array(
      // driverClass has changed to PDOMySql\Driver
      ‘driverClass’ => ‘Doctrine\DBAL\Driver\PDOMySql\Driver’,
      ‘params’ => array(
      ‘host’ => ‘localhost’,
      ‘port’ => ‘3306’,
      ‘dbname’ => ‘DB_NAME’,
      ‘user’ => ‘USER’,
      ‘password’ => ‘PASS’,

  22. web2sign said, on November 19, 2013 at 9:22 am

    I’ve able to solve the problem by merging the doctrine.global.php and doctrine.local.php and put it in global.php… i dont know why

  23. Marcos said, on November 20, 2013 at 10:19 am

    Hey man, thank you so much!

  24. Den said, on December 19, 2013 at 6:10 pm

    Thanks!!! Great THANKS MASTER!

  25. Youssoufou Yabré said, on January 24, 2014 at 10:42 pm

    Hi, follow your tutorial. I have a table named agence. when write :
    $objectManager = $this->getServiceLocator()->get(‘Doctrine\ORM\EntityManager’);
    $agences = $objectManager->getRepository(‘Application\Entity\TAgence’)->findAll();

    I got this as error

    Additional information:




    An exception occurred while executing ‘SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t0′:

    SQLSTATE[42P01]: Undefined table: 7 ERREUR: la relation « t_agence » n’existe pas
    LINE 1: …t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t…

    Any idea?

    Here is the query produced

    SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM t_Agence t0

    And I want that query

    SELECT t0.c_id_agence AS c_id_agence1, t0.c_nomAgence AS c_nomagence2, t0.c_id_agence_parent AS c_id_agence_parent3 FROM “t_Agence” t0

  26. Pomirleanu Florentin Cristinel said, on January 29, 2014 at 9:08 pm

    This is a good tutorial but can you tell me how you will make the “createAction()” for the album?

  27. Zend framework 2 | docaohuynh said, on February 4, 2014 at 2:18 pm

    […] site: http://samsonasik.wordpress.com/2013/04/10/zend-framework-2-generate-doctrine-entities-from-existing… […]

  28. danishshres said, on March 21, 2014 at 8:27 pm

    when i call the similar get method of the child entity like $row->getAlbum()->getArtist() in our case i get error

    An exception occurred while executing ‘SELECT t0.group_id AS group_id1, t0.group_name AS group_name2, t0.group_desc AS group_desc3, t0.group_image AS group_image4, t0.created_by AS created_by5, t0.created_date AS created_date6, t0.is_active AS is_active7 FROM group t0 WHERE t0.group_id = ?’ with params [1]:

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘group t0 WHERE t0.group_id = 1′ at line 1

  29. heronour said, on April 16, 2014 at 6:06 pm

    Hello sire,
    How to do with CLi to generate just a specific entity from DB ?

    • samsonasik said, on April 16, 2014 at 9:05 pm

      try try –filter=”Yourtablename”

    • moreyogesh said, on May 20, 2014 at 1:57 pm


      Are you able to generate entity for single table using –filter option?
      If Yes, Could you please let me know the Version ZF2 and Doctrine that you are using?

      I tried –filter option but still it generates entities for all the table.

  30. yogesh said, on April 16, 2014 at 7:17 pm


    I haven’t executed all the steps however I just noticed that 3rd point “Install it” is displaying HTML as it is on the screen. I have firefox V-28 browser.

    • yogesh said, on April 16, 2014 at 7:19 pm

      I guess that was happening because of some temporary issue. After refreshing few times it went away.

  31. Pham said, on April 17, 2014 at 5:04 am

    hi Malik, thank for great post!! I’m wondering how can we access Track from Album? Something like this:
    $tracks = $album->getTracks();
    foreach ($tracks as $track) {..blah blah…}

    Do we need to add some more lines like this in Album:
    * @var Collection
    * @ORM\OneToMany(targetEntity=”\Album\Entity\Track”, mappedBy=”album”))
    * @ORM\JoinColumns({
    * @ORM\JoinColumn(name=”id”, referencedColumnName=”album_id”)
    * })
    private $comment_metas;

    • samsonasik said, on April 17, 2014 at 5:46 pm

      if you already related tables correctly, personally i think generate only is enough

  32. Leo said, on April 29, 2014 at 11:00 am

    Hi Samsonasik
    I got an error:
    [Semantical Error] The annotation “@ORM\Table” in class Application\Entity\Album was never imported. Did you maybe forget to add a “use” statement for this a

    when I run ‘./vendor/doctrine/doctrine-module/bin/doctrine-module orm:generate-entities ./module/Application/src/ –generate-annotations=true’

    • samsonasik said, on April 30, 2014 at 7:12 pm

      no, you are not follow one or two step, and if you’re using windows, please using windows powershell

  33. moreyogesh said, on May 19, 2014 at 9:21 pm

    Hi there,

    Thanks a lot for detailed post. I am able to generate entities for mySQL database table.

    I am not sure if this is my mistake or something else but when I ran “convert-mapping” and “generate-entities” commands application has generated entities for all the database tables.

    I have also tried these commands using “–filter” option however it didn’t helped.

    Could you please help me out of this situation? because my application is already built in symfony 1.X and we are moving it into ZEND Framework 2 so I wanted to generate entities for single table at a time.

    Thanks once again for the post.

  34. […] we are using Doctrine2 in Zend Framework 2 project, we can use existing module named DoctrineModule that can be used to easist our job. Now I will explain about how to use […]

  35. mohammad zam zam said, on June 26, 2014 at 1:42 pm

    Assalamualaikum, Selamat menyambut Ramadhan yang bakal tiba. Pertama nya tahniah posting yang hebat2 dari Tuan.

    Saya ada masalah sedikit disini, apabila saya run command seperti yang diberikan dalam contoh diatas saya dapat return error seperti berikut :

    ‘”@php_bin@”‘ is not recognized as an internal or external command, operable program or batch file.

    minta bantuan… apa agaknya punca masalah saya ini.


    • samsonasik said, on June 27, 2014 at 2:53 am

      Wa’alaikumsalam, coba set path php.exe atau path nya php bin, register ke system path, coba google

      • mohammad zam zamm said, on June 27, 2014 at 9:01 am

        Terima kasih, tapi path untuk php.exe memang telah di set dari awal tetapi masih error..

        contoh path saya >>>


        cuma ‘php bin’ @ ‘..\php\bin’ @ php_bin memang tiada dalam computer saya .. saya install PHP yang datang sekali dengan XAMMP.

  36. Euller Cristian said, on September 22, 2014 at 7:53 am

    Dear samsonasik , the article is great, i liked a lot, thanks.

    But I am have a problem, when doctrine is create entities, the first line, refer to namespace is generate namespace Livraria\Entity\; when correct is namespace Livraria\Entity;

    Do you kwnow how i solve this question? Thanks

    • samsonasik said, on September 24, 2014 at 12:17 am

      that’s weird, maybe change the “doctrine/doctrine-orm-module” version to “0.8.*” ?

  37. Jo said, on September 23, 2014 at 4:36 pm

    Thank you so much!

  38. jangya said, on September 25, 2014 at 1:41 pm

    let’s say i have 7 tables in my db and i want to create entities for only one table say user table then what to do ?

    • samsonasik said, on September 25, 2014 at 11:14 pm

      try –filter=”Yourtablename” , please see other comment.

  39. jangya said, on September 25, 2014 at 1:50 pm

    while doing generating entities referring to 8.b cmd .resulting no metadata classes to process. can you help me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 252 other followers

%d bloggers like this: