Doctrine 2.x CRUD Doctrine 2.x CRUD codeigniter codeigniter

Doctrine 2.x CRUD


The answer is really that it's up to you. Your entities are just plain-old-PHP-objects -- so it's up to you to teach them tricks (like implementing a fromArray() method), or build up infrastructure around them.

Some options, which may or not be appropriate for your use-case:

  • Write constructors for your entities that populate properties: new Article($title, $author, $abstract, $body) or new Article($arrayOrObject)
  • Write a static factory method
  • Write your own fromArray() implementation
  • Write your own fromArray() implementation in an abstract class that all your entities inherit, and possibly override, as necessary


In every example I've seen and in my experience coding with Doctrine2, the right way to create an object from $_POST data is to set each property individually using setters in the entity classes.

fromArray() certainly seems convenient, but knowing how Doctrine2 handles associations, I couldn't see it getting you very far.

Regarding a good CRUD tutorial for Doctrine2, you might like this sample chapter from the book "Easy PHP Websites with Zend Framework." The book itself is on ZF rather than CodeIgniter, but there's very little in the sample chapter that is Zend-specific. You'll likely prefer to stay away from the z2d2 sample repository however.

Beyond that, this site has a number of helpful questions and answers on Doctrine2 that apply to a CRUD context. Continue posting and I'm sure I or one of the others here can help.


You can convert an array into object using some third party Doctrine modules like DoctrineModule, instead of implementing fromArray() or populate(). For example you can do something like:

use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;$hydrator = new DoctrineHydrator($objectManager);$data = array(    'username' => 'myuser',    'password' => 'mypass',    'email' => 'my@email.com');$user = new User();$user = $hydrator->hydrate($data, $user);$em->persist($user);$em->flush();