toArray() with Doctrine 2 and Zend Forms.

Based on a couple of assumptions (like ‘NS’ is your library that handles the Doctrine Entity Manager) ..in your abstract class, will need 2 methods:

/**
 *  A way to force eager loading.
 */
public function forceEagerLoad() {
    return true;
}

/**
 * Returns the object and its properties as an array.
 */
public function toArray() {
    $tmpMergedMappings = array();
    $tmpFieldMappings = array();
    $tmpAssocMappings = array();
    if(!$this->em) { $this->em = NS::em(); }
    $testObj = $this->em->find(get_class($this), $this->id);
    $testJob = $testObj->job;
    $tmpFieldMappings = $this->em->getClassMetadata(get_class($this))->fieldMappings;
    $tmpAssocMappings = array_keys($this->em->getClassMetadata(get_class($this))->associationMappings);
    foreach($tmpFieldMappings as $fmKey => $fmValue) {
        if(is_object($this->$fmKey)) {
            if (get_class($this->$fmKey) == "DateTime" ) {
                switch ($tmpFieldMappings[$fmKey]["type"]) {
                    case "sndatetype":
                        $tmpMergedMappings[$fmKey] = $this->$fmKey->format('m/d/Y');
                        break;
                    // handle any custom types..
                    default:
                        $tmpMergedMappings[$fmKey] = $this->$fmKey->format('Y-m-d H:i:s');
                        break;
                }
            } else {
                // presume the default _id mapping...
                $key_id = $fmKey."_id";
                $tmpMergedMappings[$key_id] = $this->$key_id->id;
            }
        } else {
            $tmpMergedMappings[$fmKey] = $this->$fmKey;
        }
    }
    foreach($tmpAssocMappings as $amKey => $amValue) {
        $tmpKey = $amValue."_id";
        switch (get_class($this->$amValue)) {
            case "Doctrine\ORM\PersistentCollection":
                // dont do anything with these right now..
                break;
            default:
                // Trigger the loading via the proxy.
                if(method_exists($this->$amValue, 'forceEagerLoad')) {
                    $forced = $this->$amValue->forceEagerLoad();
                } else {
                    // Note: these classes dont have/inherit a forceEagerLoad() method,
                    // or we are trying to call it on something not set yet.
                    //var_dump(get_class($this->$amValue));
                    //var_dump($amValue);
                }
                if($this->$amValue) {
                    if($this->$amValue->id != null) {
                        $tmpMergedMappings[$tmpKey] = $this->$amValue->id;
                    }
                }
            break;
        }
    }
    return $tmpMergedMappings;

}

..and then in your Zend Controller action, say for editing:

/**
 *
 */
public function editAction() {
    $id = $this->getRequest()->getParam('id');
    $role = $this->em->find('NS\Role', $id);
    if(empty($role)) {
        // handle error
        return $this->_helper->redirector->gotoUrl('/role');
    } else {
        $this->view->role = $role;
        $this->view->form = $this->roleForm($role->toArray());
    }
}

..and your form can look something like this:

/**
*
*/
public function roleForm($data = null) {
    $form = new Zend_Form();
    $form->setAction($this->view->baseUrl().'/role/create')->setMethod('post');
    // id (hidden)
    $id = new Zend_Form_Element_Hidden('id');
    $id->removeDecorator('Label');
    $id->removeDecorator('HtmlTag');
    $form->addElement($id);
    // name
    $name = new Zend_Form_Element_Text('name');
    $name->setLabel('Name');
    $name->setRequired(true)->addValidator('NotEmpty');
    $form->addElement($name);
    // description
    $description = new Zend_Form_Element_Text('description');
    $description->setLabel('Description');
    $description->setRequired(true)->addValidator('NotEmpty');
    $form->addElement($description);
    // submit button
    $submit = new Zend_Form_Element_Submit('Save');
    $form->addElement($submit);
    if($data) {
        $form->setDefaults($data);
        $form->populate($data);
    }
    return $form;
}

Notes from ZendCon 2010 #zendcon #zc10

Brain dumping ZendCon 2010..  If you find any broken links or have links to slides/people I wasn’t able to find, please let me know! I’m aware that some presenters are holding back their slide decks. And some folks (mostly from the IBM-i sessions) don’t seem to have blogs or twitter accounts?

Overall Impressions:

This was my first ZendCon, and my overall impression is a positive one. I walked away with a much better understand of the community and Zend’s involvement in it. I also was very fortunate to meet many new people from all over the world and of wide skillset and experience. The networking and conversations that took place outside of the sessions and at restaurants or poolside over drinks is where the real connections are made.

Some Highlights:

I didn’t know what to think:

  • The food (breakfast and lunch) where about what you would expect from a conference of this caliber. I found myself more than once wanting to leave the venue at lunch and seek real food. Of exception is the dinner provided at the receptions in the evenings.
  • The vendor expo / floor. What a sad turnout (although I was told it was on-par with last years). All you had to do was walk by the Cloud Expo hall to catch a glimpse of what a real show looks like. I was also told the prize/swag ratio was higher at last year’s conference.
  • The constant fawning by some vendors to recruit the attendees. It was like watching a Jr. High School dance. I wish I could have worn a “got telecommute?” shirt. That would have started conversations with companies I’d be interested in.

Big Letdowns:

There were two main low points for me at the conference:

  • The scheduling snafu that caused Jonathan Wage’s sessions to get canceled. One of the main reasons I was looking forward to ZendCon was the sessions on Doctrine2. I’m not sure what lead to this, and I would hope it was a fluke.
  • The Keynotes and ‘The Cloud’. I’ve been to a few internet/tech conferences, and I’d like to think I can recognize when a presentation is not reaching it’s target audience. Most of the keynotes at ZendCon were no exception. If they were related to Zend products, I’d guess most of the attendees didn’t learn anything new. If the presentation at any point used “cloud” more than once, it instantly lost credibility with me (and I was not alone as many users in the #zendcon IRC channel chimed in similar skepticism). The CloudExpo conference was next door and I wondered more than once if the speaker had wandered into the wrong hall.

Books to read:

Completely Random:

  • Robotic Vacuum Overlords (via @naderman)
  • The Nikon to Canon Ratio – why do most php developers prefer Nikon? (the ratio was 5-1 at the conference by my count)
  • Need to follow-up with David Abdemoulaie (@hobodave) – Re: Doctrine2 pagination
  • My Tweets from the week of ZendCon.
  • I need to brush up on my German and French, learn Russian.

My joind.in Comments:

Sessions and Slides:

Nov 01, 2010

Nov 02, 2010

Nov 03, 2010

Nov 04, 2010

Uncons, etc..  ping me if you have more info on these or others:

Getting Doctrine 2 and CodeIgniter 1.7 and PHP 5.3 and MySQL 5.1 and MongoDB 1.4 to play nice – across databases and objects.

Disclaimer: This post covers at a very high level an approach I’m taking into a possible solution to a challenge I’m facing at work. It should in no way be deemed the end-all, be-all, de facto standard. In fact, I’d love to hear your alternative approaches in the comments below!

There are some things that are  not covered in this post, including:

  • How to install/compile/configure PHP, CodeIgniter, Doctrine, MySQL, or MongoDB.
  • The reasons why we are using a Relation Database and a Document-based Database. No really, don’t ask.
  • How to use the command-line features of Doctrine to auto-generate your database schema.

There are some places in the code sample that you will need to edit and modify to your environment  if you copy-paste this code into your own works. Those items are in ALL_CAPS and <<CONTAINED_WITHIN_LT_GT_SIGNS>>. Just plug in your own values for these.

So,

We begin by starting off with a great example from the Doctrine v2 documentation / cookbook: Integrating with CodeIgniter. This will be the basis for our CodeIgniter Library, with a few modifications, including:

Adding in the Doctrine MongoDB ODM namespaces. You’ll noticed that we aliased the MongoDB\Configuration since it clashes with the ORM\Configuration.

<?php
use Doctrine\Common\ClassLoader,
    Doctrine\Common\Annotations\AnnotationReader,
    Doctrine\Common\Cache\ArrayCache,
    Doctrine\ORM\Configuration,
    Doctrine\ORM\EntityManager,
    Doctrine\DBAL\Logging\EchoSQLLogger,
    Doctrine\ODM\MongoDB\DocumentManager,
    Doctrine\ODM\MongoDB\Mongo,
    Doctrine\ODM\MongoDB\Configuration as MongoDBConfiguration,
    Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;

class Doctrine {

    public $em = null;
    public $dm = null;

    public function __construct()
    {
        // load database configuration from CodeIgniter
        require_once APPPATH.'config/database.php';

        // Set up class loading. You could use different autoloaders, provided by your favorite framework,
        // if you want to.
        require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';

        $doctrineClassLoader = new ClassLoader('Doctrine', APPPATH.'libraries');
        $doctrineClassLoader->register();
        $entitiesClassLoader = new ClassLoader('DW', APPPATH.'models');
        $entitiesClassLoader->register();
        $proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
        $proxiesClassLoader->register();

        // Set up caches
        $config = new Configuration;
        $cache = new ArrayCache;
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);

        // Mapping Configuration
        $driverImpl = $config->newDefaultAnnotationDriver("/<<PATH_TO_WEBSITE_CODE>>/system/application/models");
        $config->setMetadataDriverImpl($driverImpl);

        // Proxy configuration
        $config->setProxyDir('<<PATH_TO_PROXIES>>');
        $config->setProxyNamespace('Proxies');

        // Set up logger
    // commented out for now..
    //  $logger = new EchoSqlLogger;
    //  $config->setSqlLogger($logger);

        $config->setAutoGenerateProxyClasses( TRUE );

        // Database connection information
        $connectionOptions = array(
        'driver' => 'pdo_mysql',
        'user' =>     "<<DB_USERNAME>>",
        'password' => "<<DB_PASSWORD>>",
        'host' =>     "<<DB_HOST>>",
        'dbname' =>   "<<DB_NAME>>"
        );

        // Create EntityManager
        try { $this->em = EntityManager::create($connectionOptions, $config); } catch (Exception $e) { var_dump($e->getMessage()); }

        /**
        * MongoDB handler...
        */
        $configD = new MongoDBConfiguration();
        $configD->setProxyDir('<<PATH_TO_MONGODB_PROXIES>>');
        $configD->setProxyNamespace('Proxies');

        $readerD = new AnnotationReader();
        $readerD->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\');
        $configD->setMetadataDriverImpl(new AnnotationDriver($readerD, APPPATH.'models/<<NAMESPACE>>'));

        try { $this->dm = DocumentManager::create(new Mongo("mongodb://<<MONGODB_SERVER>>"), $configD); } catch (Exception $e) { var_dump($e->getMessage()); }

    }

We then add methods to wrap around and make transparent which types of objects we are dealing with. Note that we just touch on some basic functionality such as find() and persist():

public function find($_entity, $_key) {
 $result = null;
 if (property_exists($_entity, '_docORM')) {
 try { $result = $this->dm->find($_entity, $_key); } catch (Exception $e) { var_dump($e->getMessage()); }
 } else {
 try { $result = $this->em->find($_entity, $_key); } catch (Exception $e) { var_dump($e->getMessage()); }
 }
 return $result;
 }

 public function findBy($_entity, $_keys = array()) {

 $result = null;
 if (property_exists($_entity, '_docORM')) {
 try { $results = $this->dm->getRepository($_entity)->findBy($_keys); } catch (Exception $e) { var_dump($e->getMessage()); }
 } else {
 try { $results = $this->em->getRepository($_entity)->findBy($_keys); } catch (Exception $e) { var_dump($e->getMessage()); }
 }
 return $results;
 }

 public function getRepository($_entity) {
 return $this->em->getRepository($_entity);
 }

 public function persist($obj) {
 if (property_exists($obj, '_docORM')) {
 try { $this->dm->persist($obj); } catch (Exception $e) { var_dump($e->getMessage()); }
 } else {
 try { $this->em->persist($obj); } catch (Exception $e) { var_dump($e->getMessage()); }
 }
 }

 public function flush() {
 $this->dm->flush();
 $this->em->flush();
 }

}

You may have noticed that we check to see if a property is set on our object: “_docORM”. This is the flag, a static value we set, in our class that tells use to use the MongoDB ODM calls instead of the Relation Database ORM calls.

Examples of class/Entity might look like this:

A MySQL based class:

<?php
namespace <<NAMESPACE>>;

/**
 * @Entity
 * @Table(name="<<TABLE_NAME>>")
 */
class Role {

 /**
 * @Id
 * @Column(type="integer")
 * @GeneratedValue
 */
 protected $id;

 /** @Column(length=50) */
 protected $name;

 /** @Column(length=255) */
 protected $description;

 /**
 * @ManyToMany(targetEntity="Permission")
 * @JoinTable(name="role_permissions",
 *            joinColumns={@JoinColumn(name="role_id", referencedColumnName="id")},
 *            inverseJoinColumns={@JoinColumn(name="permission_id", referencedColumnName="id")}
 *           )
 */
 protected $permissions = array();

 /**
 * @ManyToMany(targetEntity="Role")
 * @JoinTable(name="role_subrole",
 *            joinColumns={@JoinColumn(name="role_id", referencedColumnName="id")},
 *            inverseJoinColumns={@JoinColumn(name="subrole_id", referencedColumnName="id")}
 *           )
 */
 protected $subroles = array();

 // A way to check for recursive sub-roles
 public function hasSubRoles() {
 if(count($this->subroles) > 0) {
 return true;
 } else {
 return false;
 }
 }
}

A MongoDB based class:

<?php
namespace <<NAMEPSACE>>;

/**
 * @Document(db="<<MONOGO_DB>>", collection="<<MONGO_COLLECTION>>")
 */
class documentRecord {

 static $_docORM = true;

 /**
 * @Id
 */
 protected $id;

 /** @String */
 protected $name;

 /** @String */
 protected $description;
}

Notice too that we are using the docblock annotation to tell Doctrine about relationships and the database/document structure. No need to manage separate YAML or XML files.

Now, from within our CodeIgniter controller, we can transparently interact with database and document-based objects, like so:


function test() {

 $orm = $this->doctrine;
$r = $orm->find('<<NAMESPACE>>\Role', <<ROLE_ID>>);
var_dump($r);

$dr = $orm->find('<<NAMSPACE>>\DocumentRecord', <<DOC_ID>>);
var_dump($dr);

}

So, what do you think?