Hello readers! The most frequently visited and linked article on my blog is by far the tutorial, how to integrate Doctrine 2 with Zend Framework 1.09. However - it is written in german and since I published it, a couple of new versions of both libraries were released. So I decided to rewrite it in english and adjust it so that it fits the most up-to-date versions of both Doctrine and the Zend Framework.

I will presume you know more or less exactly what these software packages do, and how to use them. Also, I assume that you are able to set up a virtual host by yourself. You should be familiar with how to use a command line, too!

First of all, we need to download the libraries and set up our project. Start with the Zend Framework. Go to it’s download page and download (at least) the minimal version. Right now, it is ZF 1.11.3. Unpack the download, go to a command line (whichever your system provides), change to the bin/ folder of the package and type the following lines:

chmod +x zf.sh
./zf.sh create project /path/to/App


This is what you do on a Unix shell. It is slightly different on Windows machines, there you would have to use the zf.bat file. However, you will have to figure out how to do that on your own, since I don’t work on Windows and am too lazy to google it right now.

Your project should be created now, meaning that the folder /path/to/App should contain several subfolder such as application/, library/ and so on. We create a subfolder with the name bin/ in this folder.

What has to be done next is to move all the libraries into our project. First of all, in the downloaded package of the Zend Framework, there should be a libraries/ folder containing another folder named Zend/. We move that Zend/ folder into the library/ folder of our project.

We then go on by downloading the Doctrine packages. I say packages, because we need the Doctrine ORM as well as the DBAL and the Doctrine Commons project. Luckily, all of them are included in one package, which can be downloaded on the Doctrine ORM’s download page. It is the latest Doctrine package. (As of now, it is version 2.0.1) Unpack it and simply copy the Doctrine/ folder into our project’s library/ folder.

The last step in setting up the project is to move or copy the contents of the bin/ folders of both downloaded packages into the bin/ folder that we just created in our project.

Step 2 - The configuration file

In this tutorial, I will show how to integrate Doctrine using MySQL as database engine. The config settings might be different for other engines or when you use different database interfaces. However, we open the application/configs/application.ini of our project and insert the following lines into the [production] block of the ini file.

doctrine.conn.host = '127.0.0.1'
doctrine.conn.user = 'root'
doctrine.conn.pass = ''
doctrine.conn.driv = 'pdo_mysql'
doctrine.conn.dbname = 'app'
doctrine.path.models = APPLICATION_PATH "/models"


At this point, you have to fill in your personal database connection settings. These might be completely different from the ones shown here. You should also adjust the database driver now, when you don’t want to use MySQL.

Step 3 - Bootstrapping

Now comes the fun part. We have to load all the Doctrine libraries and set them up correctly. To do that, we open the application/Bootstrap.php file of our project and fill it with the required functions. I will first post the whole file here and explain it below.

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* generate registry
* @return Zend_Registry
*/
protected function _initRegistry(){
$registry = Zend_Registry::getInstance(); return$registry;
}

/**
* Register namespace Default_
*/
{
$autoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => 'Default_', 'basePath' => dirname(__FILE__), )); return$autoloader;
}

/**
* Initialize Doctrine
* @return Doctrine_Manager
*/
public function _initDoctrine() {
// include and register Doctrine's class loader
$classLoader = new \Doctrine\Common\ClassLoader( 'Doctrine', APPLICATION_PATH . '/../library/' );$classLoader->register();

// create the Doctrine configuration
$config = new \Doctrine\ORM\Configuration(); // setting the cache ( to ArrayCache. Take a look at // the Doctrine manual for different options ! )$cache = new \Doctrine\Common\Cache\ArrayCache;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);

// choosing the driver for our database schema
// we'll use annotations
$driver =$config->newDefaultAnnotationDriver(
APPLICATION_PATH . '/models'
);
$config->setMetadataDriverImpl($driver);

// set the proxy dir and set some options
$config->setProxyDir(APPLICATION_PATH . '/models/Proxies');$config->setAutoGenerateProxyClasses(true);
$config->setProxyNamespace('App\Proxies'); // now create the entity manager and use the connection // settings we defined in our application.ini$connectionSettings = $this->getOption('doctrine');$conn = array(
'driver'    => $connectionSettings['conn']['driv'], 'user' =>$connectionSettings['conn']['user'],
'password'  => $connectionSettings['conn']['pass'], 'dbname' =>$connectionSettings['conn']['dbname'],
'host'      => $connectionSettings['conn']['host'] );$entityManager = \Doctrine\ORM\EntityManager::create($conn,$config);

// push the entity manager into our registry for later use
$registry = Zend_Registry::getInstance();$registry->entitymanager = $entityManager; return$entityManager;
}

}


The first two methods don’t have anything to to with Doctrine. We just want to use a registry in our project (later, our EntityManager instance will be stored here!) and we want to register a namespace Default_ for use in our project. These methods are pure Zend Framework-ish, so I assume you know what they do. If not, consult the ZF manual.

Now for the _initDoctrine() method. The first thing we do in line 33 is to include the class loader of Doctrine. Unfortunately, Doctrine already uses the new namespacing of PHP 5 (or 6?). The Zend Framework doesn’t. So we need another class loader with the correct namespacing scheme. We set it up in the following five lines 34-38, telling it that we need the namespace Doctrine and where the include path of the library is.

We then create a Doctrine Configuration instance and configure Doctrine (lines 41-59). Depending on how you want to control the database scheme and stuff like that, you might want to adjust some of the settings here. The ArrayCache can be changed and set to something more performant and if you don’t want to use annotations in the Entities to define the database scheme, you should use a different MetadataDriver. In this tutorial, we use both the ArrayCache and the DefaultAnnotationDriver. When we instantiate the last one, we have to tell it where our classes with the annotations (I will talk about these more, later) are.

I never really understood what the Proxy classes are. They are created at runtime by Doctrine and my guess is, they are to speed up the database interaction by sort of caching joined requests. Anyways, we need to define where these classes should be saved and what namespace that is. This is done in lines 57-59.

After that, we get our connection settings from the application.ini file and can finally create the EntityManager instance by telling it all our configurations and connection information. ThisEntityManager can be understood as the interface between the Database and our models (called Entities). We are saving it’s instance in the Zend Registry we created earlier.

And that’s it. We can now start creating Entities (models) and trying to do some database interaction!

Step 4 - The Entity

To test everything, we create a small dummy Entity. I will not go into detail on how to create Entites and define the database scheme of their tables. As we defined in the Doctrine config earlier, we want to use annotations (in the Docblock of our Entity) to define the database scheme. We create a file application/models/Test.php and fill it with the following code:

<?php

/**
* @Entity
* @Table(name="test123")
*/
class Default_Model_Test
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id; /** @Column(type="string") */ private$name;

public function setName($string) {$this->name = $string; return true; } }  As you see, we want a models with the fields id and name, id being an integer and auto_incremented and name being a string. The table name is set to test123. As you can see, an Entity is nothing more than a PHP class with some members and methods. Only the definitions for how Doctrine should build the table have to be given in the annotations. You could as well use YAML or XML files to define these. The next step is to adjust the command line tool of Doctrine to fit into our project. Step 5 - the command line tool Simply copy the following code into bin/doctrine.php replacing all of the code already in the file. <?php define('APPLICATION_ENV', 'development'); define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); // Doctrine and Symfony Classes require_once 'Doctrine/Common/ClassLoader.php';$classLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPLICATION_PATH . '/../library');
$classLoader->register();$classLoader = new \Doctrine\Common\ClassLoader('Symfony', APPLICATION_PATH . '/../library/Doctrine');
$classLoader->register();$classLoader = new \Doctrine\Common\ClassLoader('Entities', APPLICATION_PATH . '/models');
$classLoader->setNamespaceSeparator('_');$classLoader->register();

// Zend Components
require_once 'Zend/Application.php';

// Create application
$application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); // bootstrap doctrine$application->getBootstrap()->bootstrap('doctrine');
$em =$application->getBootstrap()->getResource('doctrine');

// generate the Doctrine HelperSet
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array( 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) )); \Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);


We do some bootstrapping of our project here to obtain the EntityManager instance. We then create a HelperSet with the EntityManager and run the cli tool.

To create our database table based on the Entity we created earlier, we open a command line, change into the bin/ folder of our project and run

chmod +x ./doctrine
./doctrine orm:schema-tool:create


Again, this is for the Unix shell and is different on Windows machines! Fire up your favourite database administration tool and have a look! The table test123 should have been created properly.

Step 6 - Using the database

I will just post a small example of how to use everything. Replace the content of your application/controllers/IndexController.php with the following:

<?php

class IndexController extends Zend_Controller_Action
{
public function init()
{
$registry = Zend_Registry::getInstance();$this->_em = $registry->entitymanager; } public function indexAction() {$testEntity = new Default_Model_Test;
$testEntity->setName('Zaphod Beeblebrox');$this->_em->persist($testEntity);$this->_em->flush();
}

}


This is just some quick and dirty dummy code to check if everything works. We get our EntityManager out of the registry and save it as a member of the Controller. We then create a new model (Entity), set the name and by using the EntityManager‘s persist method, we save it. EntityManager->flush() actually invokes the database action and the row should occur in our table.

Test this by simply browse to your project in your favourite webbrowser. If everything worked fine, the table should now have one entry with the name Zaphod Beeblebrox.

• Feb. 19, 2011, 6:05 p.m.

[…] I rewrote this tutorial in english and adjusted it to fit to the newest version of Doctrine and the Zend Framework. Check it out here! […]

• Feb. 20, 2011, 12:49 a.m.

Great Tutorial. Works flawless :)

• Feb. 20, 2011, 5:59 p.m.

Thanks. :)

• Feb. 25, 2011, 9:28 a.m.

Thanks alot! Very good and working tutorial. Just to spare the windows users a few seconds:

Windows console commands:
[create the project] zf create project C:\path o\App
[create schema] php doctrine orm:schema-tool:create

Not very different huh? ;-)

Tanks again,
David

• Aug. 2, 2012, 11:55 a.m.

New to ZF

I get the could not open input file: doctrine

• March 3, 2011, 3:32 p.m.

Hi Jan!
Thanks for the great tutorial. It made the first steps very easy.
Now I have to reverse engineer my models, as I do not see an option to generate them from my metadata files (which I could easily generate using your CLI script from an existing database).

Very good stuff - thanks a lot!
Kevin

• March 4, 2011, 10:14 a.m.

Thank you very much, your post is very helpful and much detail than official tutorial.
I just have one question: In my Zend Studio, if I typed \Doctrine\Common\ it always display
‘syntax error, unexpected ‘Common’ Bootstrap.php /FaceTrade/application line 34 DLTK Problem’ and some similar error tips. I do have move Doctrine into /library
doctrine.php can be successfully executed. Just not sure why the Zend Studio not work with this namespace. thanks.

• March 4, 2011, 10:27 a.m.

@John: I experienced the same problem. Right click on project =[HTML_REMOVED] Properties =[HTML_REMOVED] PHP Interpreter and change it to PHP 5.3. Default was 5.1/5.2 for me.

Just in case someone is interested. To get rid of the nasty Registry, you can also use this in your controller to fetch the Entitymanager:

$entityManager =$this-[HTML_REMOVED]getInvokeArg(‘bootstrap’)-[HTML_REMOVED]getResource(‘Doctrine’);

• March 5, 2011, 9:07 a.m.

The Registry is not nasty but a very useful tool to exchange every kind of variables/instances within the application… :P

• March 14, 2011, 3:08 p.m.

Thanks, I was looking for a zf + doctrine 2 tutorial. I have a question though, In step 1 you mention a bin/ folder that we just created in our project. Do i create it manually, and where in the dir. structure should it be, or should it have been created by the zf create project command?

• March 14, 2011, 6:16 p.m.

Hi Jeanpaul, I wrote the following before:

“Your project should be created now, meaning that the folder /path/to/App should contain several subfolder such as application/, library/ and so on. We create a subfolder with the name bin/ in this folder. “

Note, that the bin/ folder and the files that are created and copied there are only needed, if one needs to use the command line tools from Zend Framework or doctrine. I never use the former, but I like the doctrine cli tool and use it a lot.

With some minor changes in the code, you could place the bin/ folder whereever you want, it is not needed for your website to run.

• Aug. 24, 2012, 2:07 a.m.

Hi Oli,

I’m just beginning to use ZF and doctrine. I set up ZF so that I can use the zf command anywhere. I would like to try to do that with Doctrine but it seems to me that it might not be possible because the Doctrine.php is rewritten.

could you, please, help me with this?. appreciate the help.

• Aug. 24, 2012, 10:10 a.m.

Hi Charlie, I’m sorry, I don’t really get what you mean. However, I recommend updating to Zend Framework 2 and using the built-in Doctrine support. This should be much cleaner and universally useable than my tutorial.

Also, I didn’t touch the ZF for years now and am currently forgetting all about it. :(

• March 14, 2011, 6:48 p.m.

Thanks for the info. I thought there was something wrong with the path of the bin directory. The errors i recieved were actually due to the fact that i was trying to run the doctrine command on php 5.2 instead of php 5.3 so i ran into namespaces problems :-)

• April 13, 2011, 3:39 p.m.

Hi Oli, thanks a lot for your great tutorial.
But I have a problem now, and I really don’t know what it is.
The table test123 was created succesfully, but I can’t create a row inside with the entity manager. I’d appreciate any suggestions.

• April 13, 2011, 6:22 p.m.

Hi Samuel, did you maybe forget to flush the entity manager?

The persist() function does not actually execute the database queries, just kind of qeues them. They are executed when the flush() method of the Entity Manager is called.

If you did do that, can you provide any error message?

• April 13, 2011, 7:20 p.m.

Hi Oli.
It´s kind of weird. I did all what you’ve said. Of course I had flushed the entity manager, and when I executed the explorer no error messages appeared.
I can see my view, but I don´t get the new row in the table.
My doctrine.php is fine, because I can generate my table. Then I can assume that my bootstrap.php isn’t fine. ¿?
Any Ideas?

• April 13, 2011, 7:51 p.m.

Hi Oli.

I´ve solved. Thanks a lot.

Greetings.

• April 18, 2011, 7:02 p.m.

Oli,

Any chance you could zip this up into a stand alone application?

I’m thinking this shouldnt be v. difficult, that way i can see a little more what is happening.

• April 18, 2011, 7:08 p.m.

Hi Andy,

It might be allowed, but before I would do anything like this, I would read the licenses carefully.

I will have a look tomorrow, maybe it’s easier than I thought. If so, I will provide a download soon.

Regards

• April 18, 2011, 7:20 p.m.

Oli,

Thanks for this, i only ask because i’m getting:

===================

PHP Warning: Unexpected character in input: ” (ASCII=92) state=1 in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31

Warning: Unexpected character in input: ” (ASCII=92) state=1 in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31
PHP Warning: Unexpected character in input: ” (ASCII=92) state=1 in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31

Warning: Unexpected character in input: ” (ASCII=92) state=1 in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31
PHP Parse error: syntax error, unexpected T_STRING in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31

Parse error: syntax error, unexpected T_STRING in C:\workspace\ToDoList\library\Doctrinein\doctrine.php on line 31

===================

Clearly something is wrong, i’m copying and pasting from within here, maybe it’s a chat encoding issue? I will try and work out what’s happening myself, but so far so annoying :)

• April 18, 2011, 7:21 p.m.

Oh and clearly i’m working within windows. Annoyingly, this also needs to work with Linux. I’m thinking it’s probably because doing \Common will escape the C?

• April 18, 2011, 8:04 p.m.

Ha, so, it turns out i wasnt using the correct version of PHP. As we know Doctrine 2.0 works on at least 5.3 i was trying to do this on v.5.2.6 hence the fail.

I’m now getting a different error so all in all i’m starting to make progress. Thanks Oli will update if i need more help.

• April 30, 2011, 5 a.m.

Hi,

I have worked on an integration of ZF 1.X + D 2.X some time ago and I use it daily. =)
Here is the github repository: https://github.com/guilhermeblanco/ZendFramework1-Doctrine2

Also, for better separation of concerns, I also implemented a Service Layer at the top of this integration: https://github.com/guilhermeblanco/ZF1-Doctrine2-ServiceLayer

Hope it helps.

Cheers,

Guilherme Blanco - Doctrine Core Developer

• April 30, 2011, 11:19 a.m.

That indeed looks a lot more elegant than my approach, even though my code might be easier to understand for non-experts. (like me. :) )

• May 2, 2011, 4:21 p.m.

Hi Oli,

Thanks a lot for your great tutorial. every thing is working fine for me.

I am requesting post one example to get the data from table test123. Can u provide it. it will help full for all beginners like me.

Thanks,
Mahesh

• May 2, 2011, 5:42 p.m.

Dear Mahesh,

You can find an introduction on how to query the database here: http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/getting-started-xml-edition.html#list-of-bugs

The DQL (doctrine query language) is a bit complex, so you might want to read the reference to be able to use it efficiently. This tutorial’s purpose is rather to integrate doctrine within the ZF and not how to use Doctrine. That is explained very well in the Doctrine documentation.

Best regards, Oli

• July 15, 2012, 1:43 p.m.

I tried to use your advice, but I can’t select data. I don’t know why. Can you help me, please?
public function action2Action()
{
$dql = “SELECT * FROM test123”;$query = $this-[HTML_REMOVED]_em-[HTML_REMOVED]createQuery($dql);
$bugs =$query-[HTML_REMOVED]getResult();
}

I get an error on the last line of action(Application error).

• Aug. 17, 2012, 9:39 a.m.

It was my error, but there is no one guide in network, which give me all info I want. It took me much time to get this info from different sources.

• May 7, 2011, 6:22 p.m.

This is perfect :) thank you [HTML_REMOVED]3

• May 7, 2011, 6:36 p.m.

Hi Oli,
Thanks a lot, BUT there is something i want to ask you.
1. In your test.php, you use:
class Default_Model_Test as name of your class.
and in your indexAction you write:
$testEntity = new Default_Model_Test; to insert new record. How should i use this method to query a record? Should i write:$testEntity = new \Default_\Test;
$result = _em-[HTML_REMOVED]getRepository($testEntity)-[HTML_REMOVED]findOneByName(‘abc’); ???
but it didn’t work.

1. What is the purpose of namespace Default_ ???

Your tutorial does help me so much.

Best Regards

Or there

• May 7, 2011, 11:50 p.m.

Dear seferina,

Try $testEntity = new Default_Model_Test(); This is how the namespacing works in ZF. The \x\y\class.php pattern is not yet supported by the ZF autoloaders. The purpose of Default_ is, that you just have to assign some namespace name when you instantiate your autoloader. I used Default_, but usually you will use a name that fits your part of the software. So if you had some community software, you would probably have a namespace for Forum_ and one for Profile_ and so on. Different “apps” should be assigned different namespaces in general. Regards, Oli • May 8, 2011, 5:35 a.m. Hi Oli, Thanks for your prompt replay. I still have no idea hhow to make a query using under score way to instantiate class. I read on WJGILMORE page wjgilmore.com that he can instantiate class by using:$testEntity = New \Entities\Test; and to make a query he can write:

$testEntity =$em-[HTML_REMOVED]getRepository(‘Entities\Test’)

If I use Default_Model_Test, then i have no idea how to make a query to the table. Please help…

1. In your tutorial, You use Default_ as a namespace, so to instantiate class you use “Default_” as a prefix, $testEntity = New Default_Model_Test(); Is it possible if I use namespace tag in my test.php, like this: name =$string;
return true;
}
}

Oli, Many many thanks with the tutorial and support.
I appreciated so much. It helps me learn doctrine and ZF.
Best Regards

SF

• May 8, 2011, 6:04 a.m.

Hi Oli,
Sorry, for question number 2, it should be like this:

name = $string; return true; } } Is it possible to write the namespace like that. Thanks and Regards • May 8, 2011, 6:06 a.m. 1. In your tutorial, You use Default_ as a namespace, so to instantiate class you use “Default_” as a prefix,$testEntity = New Default_Model_Test();
Is it possible if I use namespace tag in my test.php, like this:

namespace Default_
/
* @Entity
* @Table(name=”test1234”)
*/
class Model_Test
{
/

* @Id @Column(type=”integer”)
* @GeneratedValue(strategy=”AUTO”)
*/
private $id; /** @Column(type="string") */ private$name;

public function setName($string) {$this-&gt;name = $string; return true; }  • May 8, 2011, 8:14 a.m. Dear seferina. It might have been wrong of me to use the word namespace, since ZF does NOT know what namespaces are and how to handle it in the PHP way. So forget all about these backslashes. The namespace functionality will be introduced in ZF 2.0. Now, ZF defines some pattern for autoloading of classes; Default_Model_Something() is translated by the autoloader into Default/Model/Something.php and the class really is named Default_Model_Something(). So whenever you want to use it, you will have to use the full classname.$testEntity = new Default_Model_Test();
$result =$_em->getRepository($testEntity)->findOneByName(‘abc’); does not work? When you want to query it is usually better to use doctrines DQL language. Here is an example: http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/getting-started-xml-edition.html#list-of-bugs There, just use Default_Model_Test() as table name and it should work. I used the word namespace because using Default_ we introduce a “quasi-namespace” since all of our classes that belong to Default_ share one folder. But it might be easier for you to forget about namespaces right now. Just trsut ZF to load the correct classes and use the full classname whenever you want to utilize them. Regards • May 8, 2011, 12:34 p.m. Hi Oli. Thanks for the prompt replay. I still need to learn to understand it all. 1. About namespace, It is avaible on the bootstrap.php, so it must be important.$autoloader = new Zend_Application_Module_Autoloader(array(
‘namespace’ =[HTML_REMOVED] ‘Default_’,
‘basePath’ =[HTML_REMOVED] dirname(FILE),
));
return $autoloader; 1. In this link, http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/getting-started-xml-edition.html#list-of-bugs On the , Entity Repository part:$product = $entityManager-[HTML_REMOVED]getRepository(‘Product’) -[HTML_REMOVED]findOneBy(array(‘name’ =[HTML_REMOVED]$productName));
Where should the “Product” php class file reside? Under Application\Model\product.php or where ??

Many Thanks, I will read more carefully, to understand it.
Thanks a lot Oli.

Best Regards
SF

• May 8, 2011, 2:47 p.m.

getRepository() expects the entityname, that is the classname of the php class.

so $result =$_em->getRepository(“Default_Model_Test”)->findOneByName(“abc”);

should work just fine. I explained in an earlier comment why I will not explain in this article how to use Doctrine, since that is not the purpose of this tutorial.

• May 8, 2011, 12:52 p.m.

Hi Oli,
I will be very appreciated if you can give us an example how to make a query using previous configuration (use test.php), but not to insert, but to quesry a record and display it.

I am waiting your post for that example.
Many many thanks Oli.

Best Regards
SF

• June 8, 2011, 11:17 p.m.

Oli,
thanks for your wonderful description. It worked very well.
I have now a new challenge, where I can’t find an answer by myself.
I want to use a @InheritanceType(“SINGLE_TABLE”) for which I need to specify the inheriting classes in Zend naming convention.
Unfortunetly the command tool can’t find the corresponding file anymore.
Can you point me in a direction? I have tried now a couple of hours, but I still don’t understand the relationship between doctrine namespaces and Zend naming convention.
Thanks,
Ben

• June 9, 2011, 10:21 p.m.

Ok, I was able to find a work-around.
The problem was that I wanted my models to be in my module directory. But the command line tool didn’t find inheriting classes anymore.
I moved now the models to the library and use proper namespaces. Now it works!
But I still have problems to understand the class loading and namespaces, especially when it comes to modules.
Thanks anyway,
Ben

• June 9, 2011, 11:58 p.m.

Dear Ben, I am glad you solved your issue. I am sorry that I didn’t reply, but I haven’t seen the comment yet. I guess I wouldn’t have been able to answer the question anyway.
Thanks for sharing,
Oli

• June 10, 2011, 10:47 a.m.

Great tutorial. It work for me!
Thank you very much

• June 15, 2011, 10:19 a.m.

Perfect tutorial. Especially for newbie like me…
Thanks a lot…

• July 8, 2011, 12:55 p.m.

Thank you, Thank you, Thank you. I have finally found someone who can make doctrine work perfectly.

• July 18, 2011, 11:12 a.m.

Thank you for this great tutorial. The best I found in the Web! I red many of them, they didn’t want to work for me…

• July 21, 2011, 2:37 p.m.

[…] Kaynak : http://www.oelerich.org/?p=315 […]

• Aug. 3, 2011, 10:04 a.m.

Thank you! Took me a few minutes to get it work using this tutorial.

• Sept. 8, 2011, 7:20 a.m.

can someone tell me how to integrate doctrine 2.1.1 with zend framework???? plzzzz

• Sept. 15, 2011, 7:31 a.m.

It shouldn’t be that different from Doctrine 2.0.x, right? What about you try it yourself and share the results? :)

• Sept. 15, 2011, 12:15 a.m.

Hi,
This is so far the best, and the easiest to understand, tutorial I have found. Great work!

But just wondering if your tutorial will work if we have doctrine 1.1.2 and php 5.2.14? If not, what changes we might need to do to make it compatible.

cheers

• Sept. 15, 2011, 7:30 a.m.

Hello devta, I started out with Doctrine 1 back then and there is plenty of tutorials on the internet how to integrate it with ZF. The Zend Framework didn’t change that much, so just try to find something via google.

Regards

• Dec. 15, 2011, 7:25 a.m.

[…] the original: Integrate Doctrine 2.0.1 with Zend Framework 1.11.3 « Oli[HTML_REMOVED]s 2 cents Bookmark on Delicious Digg this post Recommend on Facebook share via Reddit Share with Stumblers […]

• Dec. 20, 2011, 10:32 p.m.

On windows with ZendFramework 1.11 + Doctrine 2.1.5

i get this error :

[pdoexception] SQLSTATE[42000] [1049] unknown database ‘app’

I should mention that “app” database is already created with PhpAdmin on Wampserver 2.0.

So, where should i look for in order to fix it ?

Thanks

• Dec. 21, 2011, 8:12 p.m.

well, it turns out i only had to change this line

doctrine.conn.host = ‘127.0.0.1’

into this :

doctrine.conn.host = ‘localhost’

Tnen run this command from my command prompt (i’m on windows)after navigating to “bin” folder :

php doctrine orm:schema-tool:create

Indeed it creates the empty table test123 into the already created database ‘app”

After that, in my browser, i go to

http://localhost/testdoctrine/public/

which appends that record into test123 table.
(testdoctrine is, of course, the project folder on my computer)

Good tutorial

• Dec. 25, 2011, 10:29 p.m.

[…] ?imdi Base namespace i alt?na Bootstrap.php dosyas?n? olu?turuyorum.(Burada implementasyon için kaynak : http://www.oelerich.org/integrate-doctrine-2-with-zend-framework-1-11-3/ […]

• Dec. 30, 2011, 3:50 p.m.

application.ini:
resources.db.params.host = “localhost”
resources.db.params.dbname = “xxx”

bootstrap.php:
$this-[HTML_REMOVED]bootstrap(‘db’);$entityManager = \Doctrine\ORM\EntityManager::create(array(
‘pdo’ =[HTML_REMOVED] $this-[HTML_REMOVED]getResource(‘db’)-[HTML_REMOVED]getConnection() ),$config);

Now I can still use Zend_Auth_Adapter_DbTable.

• Jan. 21, 2012, 11:53 a.m.

Worked first time! Thanks a lot for this tutorial. I have been struggeling with this integration issue for quite some time. Until now that is :-)

• Jan. 26, 2012, 3:14 p.m.

thank you very much for this concise tutorial. If you have installed doctrine via pear there is no need to define a path for the ClassLoader

public function _initDoctrine() {
// include and register Doctrine’s class loader
$classLoader = new \Doctrine\Common\ClassLoader( ‘Doctrine’ ## , APPLICATION_PATH . ‘/../library/’ ## doctrine is installed via pear! • Jan. 26, 2012, 3:41 p.m. Hi My Name is Ganga Bohara and I am new to zend and Doctrine. Thanks to your tutorial that I could integrate Doctrine with Zend. But I am having problem with Many to many relationship. When I run the command “./doctrine orm:schema-tool:create” from the bin directory, it throws the following waring and the tables do not get created. Creating database schema… PHP Warning: class_parents(): Class Roles does not exist and could not be loaded in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 Warning: class_parents(): Class Roles does not exist and could not be loaded in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 PHP Warning: array_reverse() expects parameter 1 to be array, boolean given in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 Warning: array_reverse() expects parameter 1 to be array, boolean given in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 PHP Warning: Invalid argument supplied for foreach() in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 Warning: Invalid argument supplied for foreach() in /var/www/sai-library/library/Doctrine/ORM/Mapping/ClassMetadataFactory.php on line 222 Could anybody help me why its not finding the class. I have put all the entity classes inside the models folder • March 17, 2012, 11:31 a.m. thanks for great tutorial, i have run once and insert twice in mysql database? • March 17, 2012, 11:36 a.m. sori i have Resolved it, i used firephp active on chrome when i set firephp off it insert single row data • April 18, 2012, 12:50 p.m. In model we make Entity Class.$testEntity = new Default_Model_Test();
$result =$_em-[HTML_REMOVED]getRepository($testEntity)-[HTML_REMOVED]findOneByName(‘abc’); this code write in Controller action. is it possible to pick data(write DQL) from model?why pick from controller.. thanks • April 18, 2012, 3:37 p.m. I’m sorry, I don’t understand your question. • April 18, 2012, 4:49 p.m. Actually am a newbe in Zend and also Doctrine.am tryting a sample crud operation in my sample project.am not getting any sample example.I just want to simple list,add,edit,delete operation. public function indexAction() { //Pick data from Database using Doctrine and show view } public function addAction() { //Pick User input from view and add Database using Doctrine } public function editAction() { //Pick User information from database display view.User edit information and save it to Database using Doctrine } public function deleteAction() { //Delete data from database using Doctrine. } could u please put sample code in this function.. • June 17, 2012, 1:11 a.m. Hi, Great tutorial but does not work. When i get any user from entityManager ..$registry = Zend_Registry::getInstance();
$this-[HTML_REMOVED]_em =$registry-[HTML_REMOVED]entitymanager;

$user =$this-[HTML_REMOVED]_em-[HTML_REMOVED]find(‘Usuario’)-[HTML_REMOVED]findOneBy(array(
‘usuario’ =[HTML_REMOVED] $this-[HTML_REMOVED]username, ‘senha’ =[HTML_REMOVED]$this-[HTML_REMOVED]password
));
..

Exception information: Message: Class Usuario does not exist
I spent hours researching and i can not find a solution.

thanks

• July 1, 2012, 3:58 p.m.

[…] http://www.oelerich.org/integrate-doctrine-2-with-zend-framework-1-11-3/ […]

• July 26, 2012, 4 p.m.

Hey Oli,
It seems that I’m the only one to have this problem: I can do your tuto until the creation of the table, but my website doesn’t work anymore (HTTP error 500) so I’m blocked. I can’t go further.

I identified the problem in the line $entityManager = \Doctrine\ORM\EntityManager::create($conn, $config); of the bootstrap. Strange isn’t it? • July 26, 2012, 4:03 p.m. Hi G, it looks like the connection is wrong. Try putting the app in development mode by setting APPLICATION_ENV=development. Then, errors should be displayed. Also, you can have a look into the server’s error log files. There, the error messages are logged as well. • July 30, 2012, 6:05 p.m. An awesome tutorial. like some of people here, I am just beginning to use ZF and Doctrine as well. I spent several hours trying to understand the documentation of Dotrine but couldn’t get anywhere with that. This tutorial was exactly what I needed! Really appreciate it and hope to see another tutorial with ZF 2. Thanks Charlie • Aug. 17, 2012, 8:15 a.m. thanks for the info. it is very useful for me to understand easily about doctrine…… • Sept. 14, 2012, 9:25 a.m. Thank you for good tutorial • Sept. 30, 2012, 9:16 a.m. I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% sure. Any suggestions or advice would be greatly appreciated. Thank you • Sept. 30, 2012, 11:45 a.m. Hi vagex, you can get a free wordpress blog (like mine) on http://wordpress.com/. Only if you want a nice domain, you would have to pay. Regards, Oli • Oct. 20, 2012, 9:30 a.m. With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My blog has a lot of completely unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the web without my permission. Do you know any techniques to help stop content from being ripped off? I’d truly appreciate it. • Oct. 20, 2012, 10:51 a.m. I am happy when people take my code/content and reuse it. That is why I open source or publish it. • Jan. 17, 2013, 10:08 a.m. Hi Form where i found doctrine complete package, the url you provide is go to not found page. currently i found from git-hub https://github.com/doctrine/doctrine2/tree/2.3 but this is not working having Doctrine/Common/ClassLoader.php file missing and your download Url http://www.doctrine-project.org/projects/orm/download is go to not found page. please provide me correct download link if you know. • Sept. 7, 2013, 1:10 a.m. How i use ArrayCollection() in the model onetomany???? • July 15, 2014, 6:03 a.m. Great tutorials!!! But i have a query.. I don’t want to use model class name like “Default_Model_Test”. i want to use like “test” because test is my table name. So what i would be change in the bootstrap.php or application.ini settings. So that i can call it in controller with test() class Thanks.. • July 15, 2014, 9:06 a.m. Just rename your entity. As far as I remember there is no required naming scheme. • July 16, 2014, 3:02 p.m. First of all thanks for reply. But i have got same issue “Fatal error: Class ‘Entities\test not found “. Please suggest me so that i can resolve it. I am not using following code in bootstrap.php file, because i don’t want to use Default_Model_Test. i want to use Test only. /* * Register namespace Default_ * @return Zend_Application_Module_Autoloader / protected function initAutoload() {$autoloader = new Zend_Application_Module_Autoloader(array(
‘namespace’ => ‘Default
‘,
‘basePath’ => dirname(FILE),
));
return $autoloader; } Following is the my entity file which is present in model/Entities/test.php [HTML_REMOVED] use Doctrine\ORM\Mapping AS ORM; / * @ORM\Entity */ class Test { / * @ORM\Id * @ORM\Column(type=”integer”, length=11) * @ORM\GeneratedValue(strategy=”AUTO”) */ private$id;

/*
* @ORM\Column(type=”string”, length=255, nullable=true)
/
private $name; } and i am calling in controller with following code, but its not working give me an error.$testEntity = new Entities\Test();
$testEntity->setName(‘Zaphod Beeblebrox’);$this->_em->persist($testEntity);$this->_em->flush();