As Widly Inaccurate states, CodeIgniter is a wonderful PHP framework which allows rapid application development. CodeIgniter lacks a base DBLayer and ORM and makes working with multiple databases that need CRUD capabilities a pain; that’s where Doctrine comes in.
Instead of writing a comprehensive guide showing how to setup Doctrine 2 and CodeIgniter 2 together, I’m going to provide a breakdown and quick-start ZIP for those who are already aware of how to use both frameworks. A little bit of explaination, some SQL insertions, and a ZIP with well commented code later.. you’ll have Doctrine 2 and CodeIgniter 2 up and running in no-time. If you need complete breakdown explanation on how to setup CodeIgniter 2 and Doctrine 2, visit Widly Inaccurate for more details.
What’s in the ZIP?
Installation Instructions
- Unzip the “DoctrineIgnited-TLS-Web-Solutions-v1.0.zip“.
- Copy the contents of the ZIP onto your server (remote or local)
- We need to create the database and a test record. Create a database and execute the following SQL.
DROP TABLE IF EXISTS `user`; CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_username_uniq` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;INSERT INTO `user` (`id`, `username`, `password`) VALUES (7, 'Bob', NULL);
- Modify “application/config/database.php” to match your database connection information. After updating the file, browse to “http://domain.com/home/test/” to see if you’ve got everything right. If all goes well, you should see the word “Bob” appear on the screen. That means Doctrine found your db table, found the entry, updated the entry’s username, and retrieved the name again for displaying in CodeIgniter view. Classy.If something went wrong or Doctrine cannot find the “user” table, you’ll see an error message similiar to this…

(click to enlarge) - That’s it! You should be up and running. However, I do recommend you look at the next section to see a break down of how everything works.
Your website should have the “application, system, .htaccess, index.php, and license.txt” files on the root.
View the website and you should see “My Test message” come up. The default controller/action URL is “home/index/”.
DOWNLOAD THE DOCTRINE 2 AND CODEIGNITER 2 ZIP
Downloaded 3677 times.
How does it all work?
- Doctrine 2 was installed to the “application/libraries” library and was setup to use “annotations” or PHP comments to interpret how our model’s data structure is set up.
- A “User” model was created in “application/models/User.php” which annotes the database table “user” is setup through PHP comments and also has a few manually created setter and getter methods (eg: $user->getUsername()).
- The “application/config/autoload.php” was modified to autoload the “doctrine” and “session” libraries, url and form libraries (in case you want to get fancy in your views for testing).
- The “/.htaccess” and “application/.htaccess” were both modified in preparation for a “index.php”less URL. It’s just annoying and most Linux servers have mod_rewrite setup.
- The “application/config/config.php” has the “index_page” set to blank, enable_hooks turned on, encryption_key set, global_xss_filtering turned on.
- The “application/config/database.php” has the database connection information changed to match the right database connectivity.
- The “application/config/hooks.php” as the “UhOh!” error reporting added to it.
- The “application/config/routes.php” has the default controller set to “home”.
- The “application/controllers/home.php” has a few base functions and a bunch of commenting to help guide you in making magic with Doctrine 2.
- The “MY_Exceptions.php” and “MY_Controller.php” were both added to “application/core/”. MY_Exceptions extends CodeIgniter’s error reporting and MY_Controller extends CodeIgniter’s base Controller class to include a public Doctrine Entity Manager variable.
- A few files were added to “application/errors/” to spice up the error reporting HTML output thanks to UhOh!.
- The “application/hooks/uhoh.php” was added, to well, hook onto the core Exceptions.
- The “application/libraries/Doctrine/” and “application/libraries/Doctrine.php” were both added and setup and is required for Doctrine 2 to run. Doctrine.php is where most of the Doctrine setting up and configuring will take place. It inherits the DB connectivity from the “database.php” config file.
- A base view called “home.php” was added along with some style and script assets to “application/views” thanks to HTML5 Boilerplate. Those guys rock.
That’s it!
Still getting errors?
Make sure you’ve got all of the following installed or enabled on your server.
- PHP 5.3+
- Apache Rewrite module enabled
- PHP short_open_tag enabled
DOWNLOAD THE DOCTRINE 2 AND CODEIGNITER 2 ZIP (1.1mb)
Downloaded 3677 times.
sorry im noobs…
how to generate schema with doctrine schema tools
i use this code but not work……
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
$classes = array(
$em->getClassMetadata(‘models\User’),
);
$tool->createSchema($classes);
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
$classes = array(
$this->em->getClassMetadata(‘models\User’),
);
$tool->createSchema($classes);
i changed $em with $this->em
and its solved my problem
I downloaded the file to eclipse, and i get file errors
please help
Hi! I’m trying to use your setup. I’m on Windows XP using Appserv. But I’m encountering problems with the setup. The problem is described below:
[CODE]
ErrorException [ Parse Error ]: syntax error, unexpected T_STRING
FCPATH/application\controllers\home.php [ 45 ]
40 }
41
42 function newuser() {
43 /* Same as before, except we have to reference our User model
44 This shows how to add new entries */
45 $user = new models\User;
46 $user->setUsername(‘my username’);
47 $this->em->persist($user);
48 $this->em->flush();
49
50 // Test the new entry, grab the new username
{PHP internal call} » MY_Exceptions::shutdown_handler()
[/CODE]
Lol! I’m really sorry! It was my bad! I had used an older version of PHP which doesn’t support namespaces! I used PHP 5.3.0 now, and it’s working fine! I also got in to problems because I forgot to enable mod_rewrite for my Apache. Too bad Appserv doesn’t have a version which has a PHP version of lower than Alpha 6 and Greater than 5.3.0 now, so I had to use WAMP. Anyway, i just got used to it!
TO summarize, here are the important things i failed to take in to consideration in setting up this system:
1. Use PHP 5.3.0 and above
2. Enable Apache rewrite_module
3. Enable PHP short_open_tag
Thanks for everything!
Ah, yes! Thanks for pointing those out. I’ll update the guide to include your findings.
Thanks a lot for the effort!
By the way, if your app will need proxies, you have to create a writeable proxies folder under your models folder. It took me hours to realize =))
Guys, I’m having problems using DQL statements with getRepository. For example:
$users = $this->$em->getRepository(‘models\User’)->findBy(array(‘username’ => ‘asdkfjsdfasd’));
Yields the following result:
ErrorException [ Fatal Error ]: Cannot access empty property
The shorter one:
$user = $this->em->find(‘models\User’,’1′);
Has no problems though. How do i use DQL statements properly with doctrine?
Try changing “$this->$em” to “$this->em” to take care of the first error. The second error will come from trying to call the setUsername property on a non-object.
Try using “$user = $this->em->getRepository(‘models\User’)->findOneBy(array(‘username’ => ‘Bob’));” instead of “findBy” as compared to “findOneBy”. “findBy” will return the result as an array instead of just a straight up object.
What sort of errors are you experiencing?
LoL! Thank you very much! That was so stupid! I didn’t notice it. Thanks!
Hi! I have another problem.
I’m getting this weired results from these lines of code:
$posted_username = $this->input->post(‘username’);
$posted_password = $this->input->post(‘password’);
$DQLquery = “select a from models\User a WHERE a.username = :name AND a.password = :name2″;
$query = $this->em->createQuery($DQLquery);
$query->setParameters(array(
‘:name’ => $posted_username,
‘:name2′ => $posted_password,
));
$users = $query->getResult(); // array of ForumUser objects
It said:
Doctrine\ORM\Query\QueryException [ 0 ]: Invalid parameter: token :name is not defined in the query.
Damn! Once again, my bad! I found out there’s an error in the documentation from here http://bit.ly/eN6JcG. Hope this helps others.
This example was given in the documentation:
$query = $em->createQuery(‘SELECT u from ForumUser u WHERE (u.username = :name OR u.username = :name2) AND u.id = :id’);
$query->setParameters(array(
‘:name’ => ‘Bob’,
‘:name2′ => ‘Alice’,
‘:id’ => 321,
));
$users = $query->getResult(); // array of ForumUser objects
It turned out that the setParameters function should not receive tokens with the colon prefix. The correct way should be:
$query = $em->createQuery(‘SELECT u from ForumUser u WHERE (u.username = :name OR u.username = :name2) AND u.id = :id’);
$query->setParameters(array(
‘name’ => ‘Bob’,
‘name2′ => ‘Alice’,
‘id’ => 321,
));
$users = $query->getResult(); // array of ForumUser objects
I’ll be reporting this as soon as possible to the developers.
Thank you so much for providing this integration! It’s making starting up each project much easier and saved me a ton of time!
Thanks a lot for this great work, It really help me a lot
@Hanef, I’m also making an open source integration based on this one. If you have time, you can check it out at Codeplex! http://doctrineigniter.codeplex.com/ I’m planning to make this one widespread. And with community support. If you begin to understand how things work, please join us as one of the developers!
Hi! Thanks a lot about the tutorial. It really helped me a lot. I have a question: I’m trying to use Doctrine_Query in one of my controllers and i get an error:
ErrorException [ Fatal Error ]: Class ‘Doctrine_Query’ not found
What can i do?
Thank you in advance. I’m not really experienced.
You’re probably using an object that is no longer available on Doctrine 2. The Class Doctrine_Query as discussed on this Official Doctrine Documentation from Version 1.2, I think is no longer available on Version 2. You probably should just use Querybuilder from this Documentation instead http://j.mp/h4pmbK.
I am trying to move the $em->persist and $em->flush into the model so that I can have the model control the saving to the DB..
I can’t seem to work out how to load the entitymanager in the model though. $this->em = $this->doctrine->em; in the _construct of the model gives Undefined property: models\User::$doctrine
Do you have any hints for me? Thanks
@Zark. If you’re using DoctrineIgniter or this one there’s no need load the model on the entity manager from the construct. I hope this can serve as an example Model.
public function setUsername($username) { $this->username = $username; }
public function getUsername() { return $this->username; }
// Setters and Getters
public function setPassword($password) { $this->password = $password; }
public function getPassword() { return $this->password; }
public function setEmail($email) { $this->email = $email; }
public function getEmail() { return $this->email; }
public function setFacebookID($facebook_id) { $this->facebook_id = $facebook_id; }
public function getFacebookID() { return $this->facebook_id; }
public function setRefererID($referer_id) { $this->referer_id = $referer_id; }
public function getRefererID() { return $this->referer_id; }
// Magic Methods
public function __toString()
{
$retVal = "Username: " . $this->username . " ";
$retVal .= "Password: " . $this->password . " ";
$retVal .= "Email: " . $this->email . " ";
$retVal .= "Facebook ID: " . $this->facebook_id . " ";
$retVal .= "Referer ID: " . $this->referer_id;
return $retVal;
}
}
Ok. My bad, Im sorry. That seems to have been messed up in the comment system. I pasted it instead here http://pastebin.com/3xzsAw8d as an example of a model. This is what i’m using in a website I developed last month.
@Bangon Kali.
Thanks for reply.
I’ve updated your comment Bangon Kali, as the code tags you were using was [code] rather than <code>
for those who get this kind of message: trine ORM Class “not a valid entity or mapped super class” Error …
just check your caching system.
I figured out the cause of the problem was the caching system while i was using eAccelerator on MAMP i just turned it to APC which works well now
I apologize for disturbing the peace, but the problem has outgrown me, absolutely.
If you can look at:
https://groups.google.com/group/doctrine-user/browse_thread/thread/23fb347a15a97ae?hl=pl
Thank You very much for Your help
Can I see your User model code? Try pasting it into http://pastebin.com/
I guess it worked …. Link:
http://pastebin.com/zZJ5yjkq
Hi im new in CI and Doctrine,
after making those instructions:
$obj= new Home;
$obj->test();
$obj->newuser();
I get error:
ErrorException [ Notice ]: Undefined property: Home::$doctrine
FCPATH/application\core\MY_Controller.php [ 15 ]
10 parent::__construct();
11
12 /* Instantiate Doctrine’s Entity manage so we don’t have
13 to everytime we want to use Doctrine */
14
15 $this->em = $this->doctrine->em; //focused here
16 }
17
18 }
FCPATH/application\core\MY_Controller.php [ 15 ] » MY_Exceptions::error_handler(arguments)
FCPATH/application\controllers\home.php [ 10 ] » MY_Controller->__construct()
FCPATH/system\core\CodeIgniter.php [ 267 ] » Home->__construct()
FCPATH/index.php [ 163 ] » require_once(arguments)
And under this i get results:
Bob
my username
My Test message
Whats wrong?
My serv is PHP 5.3.5, mod rewrite and open short tags are enabled
Thank you so much for an excellent integration!
It works perfectly! I was able to re-write your example for CRUD in minutes and I’m up and running.
Your work was really a life saver.
I wonder if including the models generation libraries and explain how you would generate models in this setup would help others.
Even a quick post on what to add and where to generate entities could really help me. I have a monster 136 entity schema to hook up and have generated the basic YAML and XML for it, but am stuck at how to generate at least the starting Model classes from YAML or XML… Happy to add the refinement by hand.
But THANKS! again. Even if I have to hand code and re-factor the models from the unit tests it will be better than trying to set up the integration which you did so well.
Any ideas?
Hey, thanks for the mention in your post. I’ve linked back to this post here: http://wildlyinaccurate.com/codeigniter-2doctrine-2-installation/
Joseph
Wildly Inaccurate
Thanks!
Is there a Live Version somewhere that I missed or even some Screenshots?
Thank you so much! I spent days trying to get Doctrine working with Codeigniter by myself and got lost with all the different information for different versions of Doctrine and CI on the web. This is so helpful.
Thank you for this detailed step by step tutorial. The whole Doctrine2 ORM is really good and I enjoy working with it on all of my projects
.
Few weeks ago I also found ORM-Designer (http://www.orm-designer.com) project which enables you do all modeling stuff for Doctrine2 in visual editor instead of writing yaml/xml files. Maybe it will help someone else to work more efficiently as me does
please make tutorial about one to many relationship using doctrine. i get error message when doing it.
ErrorException [ Warning ]: file_put_contents(application//models/proxies\modelsaddressProxy.php) [function.file-put-contents]: failed to open stream: No such file or directory
I dunno what to do.. Thanks
Pingback: CodeIgniter 2/Doctrine 2 Installation « Wildly Inaccurate
This is great! Thanks for making my life easier.
I do have one question, though. How do I use fixtures with it?
Hi Egga,
Regarding the exception error, it looks like you’ve got two forward slashes in addition to the combination of forward and backward slashes in your file_put_contents() function. I’d start by making sure they’re all forward single slashes.
Hi, first of all, sorry for my english, im from Argentina and don’t speak english very well.
, it’s pretty cool.
Thank you for your guide and the set up project.
Here is the thing, i’ve installed it and works. I have some projects at CodeIgniter, and i recently knew about the “doctrine” and i became crazy
So, my question is… looking at the future, when a new version of codeigniters become, will not have a lot of problems for upgrade my projects with the compatibility to Doctrine? May i worry about it?
The makers of CodeIgniter and Doctrine both try pretty hard to make their code backwards compatible. In the case where there’s a complete revision in the programming and functionality of either software, it shouldn’t effect your site’s that you used the old with.
Think of it this way. CodeIgniter and Doctrine both provide a series of tools to help develop things quicker. That’s their main purpose. If they helped you accomplish that goal In a version 2 release of the code, then it’s accomplished its purpose. If a version 3 of the code comes up, that’s great, but doesn’t mean you have to.. or should in some case.. update your old site’s code to use the new version if there is a risk factor involved.
Ok, it has sense. Thank you.
Do you know where can i learn to use the doctrine 2? Is any examples (prefer with codeigniter)? If not, i will read the documentation, but i preffer examples.
Thank you again,
thanks for reply.. u say that i must make all single slashes. but i don’t do anything about that slash.. i just made this function and it automatically call the double slashes
function getById() {
$user = $this->em->find(‘models\User’, 1);
$address = $user->getAddress();
echo $address->getAddress();
}
the relationship is User manyToOne Address
please help me
As an update to all, I’ve deviated from Doctrine and CodeIgniter for now in favor (in my opinion) a more powerful platform to develop in called “Django” written in Python (far superior syntax).
I recommend everyone check it out and go through the first few pages of the tutorial (even if you don’t follow along with making the code in the examples). The real strength with Django is it’s like combining CodeIgniter, Doctrine 2, CodeIgniter’s Scaffolding (except it’s incredibly secure) all in two files of a hundred lines or so.
I’ll hopefully be doing a write-up soon of my adventures, or better yet, some video tutorials showcasing some coding from scratch.
Egga,
Without seeing the base of your code or downloading the ZIP to try it out myself, I can provide little programmatic advice from here. However, I would check out the following:
1. application/models/proxies/modelsaddressProxy.php
Make sure this file exists in the exact location it’s looking for. Uppercasing, lowercasing, etc.
2. Is it trying to include the file from your default local PHP path? Sometimes PHP likes to start at a distant include directory included with your PHP installation rather than the folder of the PHP file that is executing the method.
I’ll need more information or a ZIP to assist further.
Thanks
application/models/proxies/modelsaddressProxy.php??
i don’t know is that file exist. i don’t find that file although I redownload your zip pack. where can I upload my file to show you my code? thanks
Hi i was wondering that can i merge doctrine and CI active records to work together? For me the blessing thing in doctrine is optimistic lock mechanism, which i want to use to prevent db integrity issues when saving data. But for simple data selecting , in my opinion AR is enough and comfortable, and maybe there is also a better performance at all against using Doctrine read methods?
So, for data persistence – Doctrine, for simple data read – AR.
What do you all thing about this?
Hi,
Thanks for the integration pack.
Trying out this tutorial “http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login/comment-page-1#comment-69202″. Doesn’t seem to work.
1st of all I can’t access another class Current_User::login() as mentioned in the tutorial.It says class not found.
Thanks for any help.
Thank you! This has helped us a great deal!
Great tutorial thank you!!! I’m new with CI+Doctrine and I need some examples about, how to work with inheritance with only one example with some INSERT, so on, I’m going to be very grateful!!.
Thanks Diego