Giter Club home page Giter Club logo

zendframework1-doctrine2's Introduction

Zend Framework 1.X + Doctrine 2.X integration

ZF1-D2 is an integration tool to allow you use Doctrine 2 at the top of Zend Framework 1.

Installation

Install ZF1-D2 using Composer

Create your composer.json file

  {
      "require": {
          "guilhermeblanco/zendframework1-doctrine2": "master-dev"
      },
      "minimum-stability": "dev"
  }

Download composer into your application root

  $ curl -s http://getcomposer.org/installer | php

Install your dependencies

  $ php composer.phar install

Configuring

Doctrine 2 requires different parts of configuration.

  • Cache
  • DBAL
  • ORM

Configuring Namespaces

Since parts of Doctrine rely on specific commit pointers of individual Doctrine packages, a class loader is required to allow a customized configuration of Namespaces. One good example is default Doctrine GIT clone, which points to Doctrine\Common and Doctrine\DBAL packages through git submodules. To address this different paths issue, Bisna provides an specific class laoder configuration, which allows you to correclty map your environment. Here is an example of configuration:

; Doctrine Common ClassLoader class and file
resources.doctrine.classLoader.loaderClass = "Doctrine\Common\ClassLoader"
resources.doctrine.classLoader.loaderFile  = APPLICATION_PATH "/../library/vendor/doctrine/common/lib/Doctrine/Common/ClassLoader.php"

; Namespace loader for Doctrine\Common
resources.doctrine.classLoader.loaders.doctrine_common.namespace   = "Doctrine\Common"
resources.doctrine.classLoader.loaders.doctrine_common.includePath = APPLICATION_PATH "/../library/vendor/doctrine/common/lib/Doctrine/Common"

; Namespace loader for Doctrine\DBAL
resources.doctrine.classLoader.loaders.doctrine_dbal.namespace   = "Doctrine\DBAL"
resources.doctrine.classLoader.loaders.doctrine_dbal.includePath = APPLICATION_PATH "/../library/vendor/doctrine/dbal/lib/Doctrine/DBAL"

; Namespace loader for Doctrine\ORM
resources.doctrine.classLoader.loaders.doctrine_orm.namespace   = "Doctrine\ORM"
resources.doctrine.classLoader.loaders.doctrine_orm.includePath = APPLICATION_PATH "/../library/vendor/doctrine/orm/lib/Doctrine/ORM"

; Namespace loader for Symfony\Component\Console
resources.doctrine.classLoader.loaders.symfony_console.namespace   = "Symfony\Component\Console"
resources.doctrine.classLoader.loaders.symfony_console.includePath = APPLICATION_PATH "/../library/vendor/symfony/console/Symfony/Component/Console"

; Namespace loader for Symfony\Component\Yaml
resources.doctrine.classLoader.loaders.symfony_yaml.namespace   = "Symfony\Component\Yaml"
resources.doctrine.classLoader.loaders.symfony_yaml.includePath = APPLICATION_PATH "/../library/vendor/Doctrine/lib/vendor"

Configuring Cache

Currently, Doctrine 2 allows you to use the following different Cache drivers:

  • APC
  • Array
  • Couchbase
  • Memcache
  • Xcache

You are allowed to define multiple cache connections. If you attempt to retrieve a cache instance without a name, it will attempt to grab the defaultCacheInstance value as key. The default name of default cache instance is "default". To change it, you can simply alter the default name with the following line:

resources.doctrine.cache.defaultCacheInstance = my_cache_instance

All cache instances have a name. Based on this name you are able to correctly configure your cache instance. Here is a good example of a Memcache driver with multiple servers being used.

; Cache Instance configuration for "default" cache
resources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\MemcacheCache"
resources.doctrine.cache.instances.default.namespace    = "MyApplication_"

; Server configuration (index "0")
resources.doctrine.cache.instances.default.options.servers.0.host = localhost
resources.doctrine.cache.instances.default.options.servers.0.port = 11211
resources.doctrine.cache.instances.default.options.servers.0.persistent    = true
resources.doctrine.cache.instances.default.options.servers.0.retryInterval = 15

; Server configuration (index "1")
resources.doctrine.cache.instances.default.options.servers.1.host = localhost
resources.doctrine.cache.instances.default.options.servers.1.port = 11211
resources.doctrine.cache.instances.default.options.servers.1.persistent    = true
resources.doctrine.cache.instances.default.options.servers.1.weight        = 1
resources.doctrine.cache.instances.default.options.servers.1.timeout       = 1
resources.doctrine.cache.instances.default.options.servers.1.retryInterval = 15
resources.doctrine.cache.instances.default.options.servers.1.status        = true

Configuring DBAL

Doctrine DataBase Abstraction Layer follows the same idea of Cache drivers.

; Points to default connection to be used. Optional if only one connection is defined
resources.doctrine.dbal.defaultConnection = default

; DBAL Connection configuration for "default" connection
;resources.doctrine.dbal.connections.default.id = default
;resources.doctrine.dbal.connections.default.eventManagerClass  = "Doctrine\Common\EventManager"
;resources.doctrine.dbal.connections.default.eventSubscribers[] = "DoctrineExtensions\Sluggable\SluggableSubscriber"
;resources.doctrine.dbal.connections.default.configurationClass = "Doctrine\DBAL\Configuration"
;resources.doctrine.dbal.connections.default.sqlLoggerClass     = "Doctrine\DBAL\Logging\EchoSQLLogger"

; Database configuration
;resources.doctrine.dbal.connections.default.parameters.wrapperClass = ""
resources.doctrine.dbal.connections.default.parameters.driver   = "pdo_mysql"
resources.doctrine.dbal.connections.default.parameters.dbname   = "fmm"
resources.doctrine.dbal.connections.default.parameters.host = "localhost"
resources.doctrine.dbal.connections.default.parameters.port = 3306
resources.doctrine.dbal.connections.default.parameters.user = "root"
resources.doctrine.dbal.connections.default.parameters.password = "password"
;resources.doctrine.dbal.connections.default.parameters.driverOptions.ATTR_USE_BUFFERED_QUERIES = true

Configuring ORM

TBD

Using

Accessing Doctrine Container

It is strongly recommended to encapsulate the default Zend_Controller_Action class into our project's one. By using this encapsulation, it allows you to include your own support without having to hack default Zend implementation.

A very rudimentary implementation of a possible base class is here:

<?php

namespace Bisna\Controller;

/**
 * Action class.
 *
 * @author Guilherme Blanco <[email protected]>
 */
class Action extends \Zend_Controller_Action
{
    /**
     * Retrieve the Doctrine Container.
     *
     * @return Bisna\Doctrine\Container
     */
    public function getDoctrineContainer()
    {
        return $this->getInvokeArg('bootstrap')->getResource('doctrine');
    }		
}

Doctrine Container API

The following API exposes all available Doctrine Container methods to be used by developers:

<?php

namespace Bisna\Application\Container;

/**
 * Doctrine Container class.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link www.doctrine-project.org
 *
 * @author Guilherme Blanco <[email protected]>
 */
class DoctrineContainer
{
    /**
     * Retrieve Cache Instance based on its name. If no argument is provided,
     * it will attempt to get the default Instance.
     * If Cache Instance name could not be found, NameNotFoundException is thrown.
     *
     * @throws Bisna\Application\Exception\NameNotFoundException
     *
     * @param string $cacheName Optional Cache Instance name
     *
     * @return Doctrine\Common\Cache\Cache Cache Instance
     */
    public function getCacheInstance($cacheName = null);

    /**
     * Retrieve DBAL Connection based on its name. If no argument is provided,
     * it will attempt to get the default Connection.
     * If DBAL Connection could not be retrieved, NameNotFoundException is thrown.
     *
     * @throws Bisna\Application\Exception\NameNotFoundException
     *
     * @param string $connName Optional DBAL Connection name
     *
     * @return Doctrine\DBAL\Connection DBAL Connection
     */
    public function getConnection($connName = null);

    /**
     * Retrieve ORM EntityManager based on its name. If no argument provided,
     * it will attempt to get the default EntityManager.
     * If ORM EntityManager could not be retrieved, NameNotFoundException is thrown.
     *
     * @throws Bisna\Application\Exception\NameNotFoundException
     *
     * @param string $emName Optional ORM EntityManager name
     *
     * @return Doctrine\ORM\EntityManager ORM EntityManager
     */
    public function getEntityManager($emName = null);
}

zendframework1-doctrine2's People

Contributors

ajlozier avatar anusch-athari avatar bgetsug avatar bountin avatar chriswoodford avatar dorongutman avatar dteoh avatar dustinmoorman avatar emiliodeg avatar guilhermeblanco avatar holtkamp avatar jaspernbrouwer avatar jonathan-dh avatar kipelovets avatar lukaslabryszewski avatar maks3w avatar miau avatar mikaelkael avatar ramondelafuente avatar rdohms avatar yourwebmaker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zendframework1-doctrine2's Issues

Gedmo translatable listener

Hello!!

I'm trying to use the listener translatable of Gedmo.

I saw how it works in various unit tests but I don't find how get access to the listener to change the locale:

$article = $this->em->getRepository(self::ARTICLE)->find(1);
$this->translatableListener->setTranslatableLocale('de');
$article->setName('name in de');
$article->setContent('content in de');
$article->setTitle('title in de');

$this->em->persist($article);
$this->em->flush();
$this->em->clear();

Can you help me guys?

Do I need to namespace every doc-block notation?

Is is now required to namespace every notation like this?

/**
 * @ORM\ManyToOne(targetEntity="Role")
 * @var type 
 */

given You use
use Doctrine\ORM\Mapping as ORM;

Is there any workaround for this?

How to generate entities ?

I have configured the project according to your instruction. Now project is running and I want to create Entities..

MappingDriverChain Issue using doctrine 2.2

I'm trying bisna with doctrine 2.2 But I found this error
Catchable fatal error: Argument 1 passed to Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain::addDriver() must implement interface Doctrine\Common\Persistence\Mapping\Driver\MappingDriver, instance of Doctrine\ORM\Mapping\Driver\AnnotationDriver

While AnnotationDriver implements MappingDriver I don't know why this producing that error?

Thank you

Any license on this repo?

Hey Guilherme,

Any chance of adding a license to this package? I've been using it here and there but a few people have mentioned that there's no license attached and that might be something to look at.

I didn't wanna be presumptuous and add a PR with a license attached.

Thanks!

Upgrade from 2.0->2.3

Everything seems to be in place; however, the annotations are not auto-loading and I can't figure out why. If I declare a use statement for them in the entity, then they work ... however; I'd prefer to not have to go through all my entities and do that. It seems there should be some way via configuration to tell it to autoload the doctrine annotation and use them as the default. I see it is requiring them.

I asked in the chat channel, but no response. I've spent a few hours trying to figure it out and failed. Any assistance is appreciated, it feels like I'm missing something simple and straightforward.

Assign event manager to entity managers (inc fix)

Hi,

We needed to assign an event manager to an entity manager and found we needed to extend your library.

There is one extra hurdle in that the event manager object used by the entity manager and dbal connection have to be the same thing, otherwise a mismatch exception is thrown.

I have never used github to submit changes before so I thought I would create an issue with the change I made. Sorry if this not the best way.

Any questions about my changes or suggestions very welcome:


Index: Bisna/Application/Container/DoctrineContainer.php
===================================================================
--- Bisna/Application/Container/DoctrineContainer.php   (revision 10493)
+++ Bisna/Application/Container/DoctrineContainer.php   (working copy)
@@ -67,6 +67,11 @@
      */
     private $entityManagers = array();
 
+    /**
+     * @var object Doctrine EventManager.
+     */
+    private $eventManager;
+
 
     /**
      * Constructor.
@@ -362,7 +367,7 @@
         return \Doctrine\DBAL\DriverManager::getConnection(
             $config['parameters'],
             $this->startDBALConfiguration($config),
-            $this->startDBALEventManager($config)
+            $this->startEventManager($config)
         );
     }
 
@@ -390,21 +395,31 @@
     /**
      * Initialize the EventManager.
      *
-     * @param array $config DBAL Connection configuration.
+     * @param array $config DBAL / ORM Connection configuration.
      *
      * @return Doctrine\Common\EventManager
      */
-    private function startDBALEventManager(array $config = array())
+    private function startEventManager(array $config = array())
     {
-        $eventManagerClass = $config['eventManagerClass'];
-        $eventManager = new $eventManagerClass();
+        // If no event manager class defined then return null
+        if (isset($config['eventManagerClass']) === false) {
+            return null;
+        }
+
+        // Create new event manager if not previously created
+        if (isset($this->eventManager) === false) {
+            $eventManagerClass = $config['eventManagerClass'];
+            $this->eventManager = new $eventManagerClass();
+        }
 
         // Event Subscribers configuration
-        foreach ($config['eventSubscribers'] as $subscriber) {
-            $eventManager->addEventSubscriber(new $subscriber());
+        if (isset($config['eventSubscribers']) === true) {
+            foreach ($config['eventSubscribers'] as $subscriber) {
+                $this->eventManager->addEventSubscriber(new $subscriber());
+            }
         }
 
-        return $eventManager;
+        return $this->eventManager;
     }
 
     /**
@@ -473,9 +488,13 @@
      */
     private function startORMEntityManager(array $config = array())
     {
+        // Get Event Manager for Entity Manager
+        $evm = $this->startEventManager($config);
+
         return \Doctrine\ORM\EntityManager::create(
             $this->getConnection($config['connection']),
-            $this->startORMConfiguration($config)
+            $this->startORMConfiguration($config),
+            $evm
         );
     }
/code>

Thanks for your hard work we find it very useful.

Cheers

Alex

Custom column types missing

Opened as per our email conversation.

You had missed a way to define custom column types for the DoctrineContainer resource.
Probably could put it in around line 530 in Bisna/Application/Container/DoctrineContainer.

application.ini

resources.doctrine.orm.entityManagers.default.DQLTypes. = "CustomDoctrine/ORM/Type/CustomType"

This Simply Doesn't Work

I'm trying to get this to work, have downloaded it and created a new project - and have downloaded the latest Doctrine 2.2, and the pathways simply don't match.

For example the latest download of Doctrine 2.2 doesn't have a 'vendor' folder in it?

I change all the application.ini pathways to point to the new relevant pathways, and now get:

PHP Fatal error: Class 'Memcache' not found in m:\Bisna\library\Bisna\Doctrine\Container.php on line 485.

Can anyone point me in the direction of a tutorial that shows how to get this awesome piece of code up and running?

Integration with Doctrine 2.1

I'm trying to setup some unit tests in order to discover Doctrine, but i cannot use annotation, for an unknown reason. Am i wrong, or there is a real issue with Doctrine 2.1

I put a very simple Entity, with simple annotation :
@entity
@table(name="products")

But i keep having the following error :
Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@table" in class Hipopo\Entity\User was never imported. Did you maybe forget to add a "use" statement for this annotation?

As i understand Annotation are hard to understand from my setup, but i don't see where it failed.

About my setup, i did checkout the latest Doctrine version, and linked them in library (svn external urls), so my setup, is slightly :
./library/Doctrine/ORM point to ORM release library directory of Doctrine
./library/Doctrine/DBAL point to DBAL release library directory of Doctrine
./library/Doctrine/Common point to Common release library directory of Doctrine

so in my application i have some lines like :
resources.doctrine.classLoader.loaders.doctrine_common.namespace = "Doctrine\Common"
resources.doctrine.classLoader.loaders.doctrine_common.includePath = APPLICATION_PATH "/../library"

Tell me if i'm wrong somewhere

And i must admit i'm quite bugged by the path you use in the packaged configuration file, (" ./library/vendor/Doctrine/lib/vendor/doctrine-common/lib/ "). Why those path are so strange ?

Doctrine\DBAL\Types\Type::overrideType()

It would be nice to have some config entry for using Doctrine\DBAL\Types\Type::overrideType().

Currently the config entry:
doctrine.dbal.connections.next.types.TYPE = CLASSNAME
will add the type using Doctrine\DBAL\Types\Type::addType().

The small patch below will use overrideType() if the type already exists, and addType() if not.
This eliminates the need for an additional config entry (it is sufficient for me, but I'm not sure others will like it).

435c435,439
<             Type::addType($name, $className);

---
>             if (Type::hasType($name)) {
>                 Type::overrideType($name, $className);
>             } else {
>                 Type::addType($name, $className);
>             }

Thanx!

Doctrine 2.1.6 works, 2.2 doesn't (Annotations not imported)

Hi,

iam using the newest Version of the bisna-library. In Doctrine 2.1.6 the integration works properly, but when i upgrade to Doctrine 2.2 the annotation-reading fails. I get the following:

Semantical Error] The annotation "@table" in class Project\Entity\AclRoles was never imported. Did you maybe forget to add a "use" statement for this annotation?

What can i do here?

Problem with integration

Hi. im a new user of Bisna and im trying to integrate bisna with doctrine 2.2 and zend 1.11 for tree days with no sucess.

i follow the instructions in readme but.

I create my IndexController using the example in readme but i get an stack trace

"Message: Invalid controller class ("IndexController")"

Sorry with my english i`m from brazil.

the code:

view->msg = "Test"; } ``` }

Doctrine/Container doesn't setup memcached

method startCacheInstance in Doctrine/Container.php only setup MemcacheCache and not MemcachedCache:

    if (method_exists($adapter, 'initialize')) {
        $adapter->initialize($config);
    } else if ($adapter instanceof \Doctrine\Common\Cache\MemcacheCache) {
        // Prevent stupid PHP error of missing extension (if other driver is being used)
        $memcacheClassName = 'Memcache';
        $memcache = new $memcacheClassName();

        // Default server configuration
        $defaultServer = array(
            'host'          => 'localhost',
            'port'          => 11211,
            'persistent'    => true,
            'weight'        => 1,
            'timeout'       => 1,
            'retryInterval' => 15,
            'status'        => true
        );

        if (isset($config['options']['servers'])) {
            foreach ($config['options']['servers'] as $server) {
                $server = array_replace_recursive($defaultServer, $server);

                $memcache->addServer(
                    $server['host'],
                    $server['port'],
                    $server['persistent'],
                    $server['weight'],
                    $server['timeout'],
                    $server['retryInterval'],
                    $server['status']
                );
            }
        }

        $adapter->setMemcache($memcache);
    }

Not Doctrine/Common 2.0.x compatible (anymore ?)

The container calls Doctrine/Common/Annotation/CachedReader.php, which doesn't exist in the 2.0.6 branch (and bundle).
The simplest way to handle this would be to specify the dependency in the Readme. The really nice way would be to make a 2.0.x branch ;)

Problem with proxy loading

Hey Guys,

run into this problem when using Zend_Session:
http://groups.google.com/group/doctrine-user/browse_thread/thread/334c3136ccf21630

In my Proxy dir I have a file:
__CG__IAAEntityRole.php

and I get error:
Failed opening 'IAA\Entity\Proxy__CG__\IAA\Entity\Role.php' for inclusion

As You can see, something is wrong with either generating the proxy class or loader. Any advise on this issue would be helpfull.
I my add, that changing Proxy namespace to one level only does not help (as some suggest).

Create config option to deal with the order of Entity Managers.

If your application has to deal with multiple Entity Managers (EMs), such as one per application module, then you should be able to define the order in which each EM has to be executed, so that things like database referential integrity can be taken into account.

This is especially desirable for CLI scripts, which will have to iterate through multiple EMs and execute a given fuction, such as database reset (drop schema + create schema).

Composer autoloader

I'm not clear if this is an issue, or if I'm just missing something.

I had trouble getting Bisna's Doctrine.php to autoload when everything is installed via composer. I kept getting "unable to resolve plugin". My workaround was to use a full path for the Bisna plugin in my application.ini:

pluginPaths.Bisna\Application\Resource\ = APPLICATION_PATH "vendor/guilhermeblanco/zendframework1-doctrine2/library/Bisna/Application/Resource"

. . . which really, works fine, though it seems to me that the Composer autoloader should help out here. I am including that in my ZF index.php. Any idea why it's not working in this instance?

Add documention for Hydrators and Naming Strategy

Hi,
I am configuring my own Hydrators and Naming Strategy in Bootstrap.php with :
$namingStrategy = new OAMNamingStrategy();
$em->getConfiguration()->setNamingStrategy($namingStrategy);

$em->getConfiguration()->addCustomHydrationMode('NumHydrator', 'My\Doctrine\Hydrator\NumHydrator');
$em->getConfiguration()->addCustomHydrationMode('ColumnHydrator', 'My\Doctrine\Hydrator\ColumnHydrator');

I wasn't able to find how to do it in application.ini (something like : resource.doctrine.orm.entityManagers.default.naming_strategy = "My\Doctrine\NamingStrategy\OAMNamingStrategy" ??) and google didn't help me.
Does someone know how to do that? Maybe it could be added in the application.ini given, as an exemple...
Thanks!
Thanks

Doctrine 2.5?

Hi.

This works on Doctrine2.5?
I can't update a project from Doctrine 2.1 to 2.5.

Support for SecondLevelCache

Now SecondLevelCache is stable with the release of Doctrine ORM 2.5.0, this might be useful to adopt in the Container::startORMConfiguration() function.

ORM:info

If im correct there is a new command in 2.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.