Skip to main content
Image for post: Zend2 and Doctrine2 tricks

Zend2 and Doctrine2 tricks

I am trying to work hard with Zend framework and taking advantage using a powerful ORM like Doctrine2. I have many difficulties but after many research and coding, I've gathered some useful tricks and links.

Generate entities from database

Your application must be connected to the database and you must set the doctrine parameters on your ZF2 app. This can be tricky and difficult: I wanted to generate entities to put on the Application module and "Entity"directory. I've obtained many errors but at the end I've saved these two instructions from CLI. The first one generate entities with PHP vars that match the database fields:


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

The second one update your entieties (PHP files) adding getters and setters. Note: this operation add the funcions methods get and set for each field and var on your file. The function setId will NOT be added. So you have to add it manually if you need. If you update your DB table, you can generate the entities but remember to merge your manual udpates or you will loose them. Remember to delete old files from the Entity dir before generating new files again.


php vendor\doctrine\doctrine-module\bin\doctrine-module.php orm:generate-entities .\module\Application\src\ --generate-annotations=true

I use windows so you use linux or MAC, you can use / instead \. This works for me but something is strange: the first one use vendor\bin doctrine-module command. The second one uses the file on vendor\doctrine\doctrine-module. In fact, you have 2 directories with almost the same file when you download your doctrine files with composer...

SELECT with WHERE CONDITIONS

Now we have our entities from the database and we don't need to write them manually any more. Doctrine can take the entity resource and use it :


$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$user1 = $this->em->getRepository('Application\Entity\Users')->find(1);

$user1 = $objectManager->find('User', 1);
var_dump($user1->getFullName());
$user2 = $objectManager->getRepository('User')->findOneBy(array('fullName' => 'Andrea Fiori'));
var_dump($user2->getFullName());

NOTE: this example is taken from the Marco Pivetta's presentation. If you need to invoke the service locator from anywhere, you need to have a module like the Service Locator Factory.

THE SHOW MUST GO ON!

This is only the beginning! With Doctrine you will have a lot features and goodies like Paginator, Hydrator, APIs and the possibility to connect Postgree SQL, Mongo DB and some other.

RESOURCES

 

Share this post

This website and/or any sub domains use cookies to understand how you to improve your experience.