Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating Zend Framework 1.11 with MongoDB using Doctrine ODM

Does any know of a way to integrate zend framework with Mongo using Doctrine 2 beta ODM? I've viewed the zendcast video on integrating with Doctrine 2 ORM for MySQL but Bisna was never updated to support Mongo.

I guess I can try and hack Bisna to get it working but I'd like to know if someone else has already found a way to get it working.

like image 242
danny Avatar asked Feb 25 '23 16:02

danny


1 Answers

It's pretty easy to write a Zend Bootstrap Resource.

Here is one I use:

<?php

namespace Cob\Application\Resource;

use Doctrine\Common\Annotations\AnnotationReader,
    Doctrine\ODM\MongoDB\DocumentManager,
    Doctrine\MongoDB\Connection,
    Doctrine\ODM\MongoDB\Configuration,
    Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver,
    Doctrine\Common\EventManager;

/**
 * Creates a MongoDB connection and DocumentManager instance
 *
 * @author Andrew Cobby <[email protected]>
 */
class Mongo extends \Zend_Application_Resource_ResourceAbstract
{

    /**
     * @return \Doctrine\ODM\MongoDB\DocumentManager
     */
    public function init()
    {
        $options = $this->getOptions() + array(
            'defaultDB'          => 'my_database',
            'proxyDir'          => APPLICATION_PATH . '/domain/Proxies',
            'proxyNamespace'    => 'Application\Proxies',
            'hydratorDir'       => APPLICATION_PATH . '/domain/Hydrators',
            'hydratorNamespace' => 'Application\Hydrators'
        );

        $config = new Configuration();
        $config->setProxyDir($options['proxyDir']);
        $config->setProxyNamespace($options['proxyNamespace']);
        $config->setHydratorDir($options['hydratorDir']);
        $config->setHydratorNamespace($options['hydratorNamespace']);
        $config->setDefaultDB($options['defaultDB']);

        $reader = new AnnotationReader();
        $reader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\');
        $config->setMetadataDriverImpl(new AnnotationDriver($reader, $this->getDocumentPaths()));

        $evm = new EventManager();
        $evm->addEventSubscriber(new SlugSubscriber());

        return DocumentManager::create(new Connection(), $config, $evm);
    }

    public function getDocumentPaths()
    {
        $paths = array();
        foreach(new \DirectoryIterator(APPLICATION_PATH . '/modules') as $module){
            $path = $module->getPathname() . '/src/Domain/Document';

            if((!$module->isDir() || $module->isDot()) || !is_dir($path)){
                continue;
            }

            $paths[] = $path;
        }

        if(!count($paths)){
            throw new \Exception("No document paths found");
        }

        return $paths;
    }

}

Though you'll have to update the getDocumentPaths() method to suit your application directory structure.

like image 94
Cobby Avatar answered Mar 05 '23 16:03

Cobby