Being inspired by the wonderful series of articles/screencasts on the nettuts website called CodeIgniter From Scratch I decided to write my own series on using CodeIgniter and Doctrine together to build a functional website in a series of tutorials.
In this first part of series, I will show you how to create a basic CodeIgniter install and add Doctrine as a plug-in.
"CodeIgniter and Doctrine from Scratch" Series:
Why add Doctrine to CodeIgniter?
Before we get started, first let me explain the reason I am doing this. Doctrine is an Object Relational Mapper for PHP. It’s OK if you don’t know this term. It basically means that you can map your database tables to classes in your web application. And instances of these classes (i.e. objects) represent records in the database.
This makes it very easy to create, read, update and delete records from the database, while handling them almost like regular objects, so you don’t even have to write any queries. It will also handle relationships between your tables. There are several other benefits that I will not get into until later in these tutorials. See the Doctrine Introduction, if you would like more info right now.
Here is an illustration I put together, that might give you a visual picture.

First Step: Setup your development environment
If you already have a web server with PHP and MySQL setup, you can skip some of this.
- Download and install WAMP (for Mac: MAMP)
Warning Skype Users: You must shutdown Skype first before you start up WAMP, due to a port conflict. After WAMP starts up, you can open Skype again. - Visit http://localhost/ in your browser to make sure it’s working
- Open the “www” folder under the WAMP installation.
- Create a folder named “ci_doctrine_day1″. We will put our files here.
Install CodeIgniter
- Download CodeIgniter
- Extract and copy the contents into your new “ci_doctrine_day1″ folder.
- You may delete the “user_guide” folder.
Your new folders should look like this:

You should see this:

CodeIgniter Crash Course: Controllers
Controllers are called by CodeIgniter on every page load.
They are located under:
system/application/controllers/
The url structure looks like this:
http://localhost/ci_doctrine_day1/index.php/CONTROLLER_NAME/FUNCTION_NAME
For example if you open this url:
http://localhost/ci_doctrine_day1/index.php/hello/world
CodeIgniter will look for a controller class named “Hello” and call it’s method named “world()”.
So let’s create our first controller.
Our First Controller
- Create this file: system/application/controllers/hello.php
<?php
// system/application/controllers/hello.php
class Hello extends Controller {
function world() {
echo "Hello CodeIgniter!";
}
}
You should see:
Hello CodeIgniter!
Please Note:
- The class must extend Controller.
- The class name must be capitalized.
- The file name must be lowercase.
Recommended Reading:
Install Doctrine
CodeIgniter allows us to add plug-ins. That’s how we will be installing it.
- Create this folder: system/application/plugins
- Create this folder: system/application/plugins/doctrine
- Download Doctrine
- Extract the files. Find the folder named “lib” and copy it to system/application/plugins/doctrine.
Now your folders should look like this:

- Create the plug-in file: system/application/plugins/doctrine_pi.php
<?php
// system/application/plugins/doctrine_pi.php
// load Doctrine library
require_once APPPATH.'/plugins/doctrine/lib/Doctrine.php';
// load database configuration from CodeIgniter
require_once APPPATH.'/config/database.php';
// this will allow Doctrine to load Model classes automatically
spl_autoload_register(array('Doctrine', 'autoload'));
// we load our database connections into Doctrine_Manager
// this loop allows us to use multiple connections later on
foreach ($db as $connection_name => $db_values) {
// first we must convert to dsn format
$dsn = $db[$connection_name]['dbdriver'] .
'://' . $db[$connection_name]['username'] .
':' . $db[$connection_name]['password'].
'@' . $db[$connection_name]['hostname'] .
'/' . $db[$connection_name]['database'];
Doctrine_Manager::connection($dsn,$connection_name);
}
// CodeIgniter's Model class needs to be loaded
require_once BASEPATH.'/libraries/Model.php';
// telling Doctrine where our models are located
Doctrine::loadModels(APPPATH.'/models');
// (OPTIONAL) CONFIGURATION BELOW
// this will allow us to use "mutators"
Doctrine_Manager::getInstance()->setAttribute(
Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
// this sets all table columns to notnull and unsigned (for ints) by default
Doctrine_Manager::getInstance()->setAttribute(
Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS,
array('notnull' => true, 'unsigned' => true));
// set the default primary key to be named 'id', integer, 4 bytes
Doctrine_Manager::getInstance()->setAttribute(
Doctrine::ATTR_DEFAULT_IDENTIFIER_OPTIONS,
array('name' => 'id', 'type' => 'integer', 'length' => 4));
Read the comments in the code for explanations. However, don’t worry if you don’t understand all of it for now.
Database Setup and Configuration
- Open phpMyAdmin: http://localhost/phpmyadmin/
- Create a database named “ci_doctrine”

- Edit file: system/application/config/database.php
- Find the lines below and input the values.
// in system/application/config/database.php // ... $db['default']['hostname'] = "localhost"; $db['default']['username'] = "root"; $db['default']['password'] = ""; $db['default']['database'] = "ci_doctrine"; // ...
We just edited the database configuration file of CodeIgniter.
More Configuration
Almost done.
config.php
- Edit file: system/application/config/config.php
// in system/application/config/config.php // ... $config['base_url'] = "http://localhost/ci_doctrine_day1/"; // ...
Now CodeIgniter knows the url of our site.
autoload.php
- Edit file: system/application/config/autoload.php
// in system/application/config/autoload.php
// ...
$autoload['plugin'] = array('doctrine');
// ...
This makes sure the Doctrine plug-in is always loaded.
Finished!
Now we’re ready to rock. Let’s start testing our setup.
Our First Doctrine Model
Create a user Table
- Open phpMyAdmin: http://localhost/phpmyadmin/
- Go to database “ci_doctrine”
- Create a table named “user” with columns:
id => int, primary key, auto_increment,
username => varchar(255), unique,
password => varchar(255),
first_name => varchar(255),
last_name => varchar(255)
You may use this query:
CREATE TABLE `ci_doctrine`.`user` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 255 ) NOT NULL , `password` VARCHAR( 255 ) NOT NULL , `first_name` VARCHAR( 255 ) NOT NULL , `last_name` VARCHAR( 255 ) NOT NULL , UNIQUE ( `username` ) )

Create the Model
- Create file: system/application/models/user.php
<?php
// system/application/models/user.php
class User extends Doctrine_Record {
public function setTableDefinition() {
$this->hasColumn('username', 'string', 255);
$this->hasColumn('password', 'string', 255);
$this->hasColumn('first_name', 'string', 255);
$this->hasColumn('last_name', 'string', 255);
}
}
Note:
- We extend Doctrine_Record, instead of Model (which you normally would with CodeIgniter models).
- Inside the function setTableDefinition() we need to define the table structure.
- By default, Doctrine will look for a table with same name as the class. In this case: “user”. (this can be changed)
- In our doctrine_pi.php file above in this tutorial, we specified for a default primary key named “id”. Therefore we don’t need to put it again in our User class.
Testing the Model: Add Some Users
- Edit our controller we created earlier: system/application/controllers/hello.php
<?php
// system/application/controllers/hello.php
class Hello extends Controller {
function world() {
echo "Hello CodeIgniter!";
}
function user_test() {
$u = new User;
$u->username = 'johndoe';
$u->password = 'secret';
$u->first_name = 'John';
$u->last_name = 'Doe';
$u->save();
$u2 = new User;
$u2->username = 'phprocks';
$u2->password = 'mypass';
$u2->first_name = 'Codeigniter';
$u2->last_name = 'Doctrine';
$u2->save();
echo "added 2 users";
}
}
We just generated 2 objects, and populated them with some data. Simply calling save() should save them into our database.
Note:
- We are able to access the fields as parameters (e.g. $u->username), even though we did not create these as class parameters. Isn’t Doctrine nice?
- If you are familiar with CodeIgniter, you might remember that you need to call $this->load->model() function to load models. However since we registered the autoload function of Doctrine, just saying “new User;” is enough.
- We didn’t create the “save()” function, because it comes from the Doctrine_Record class we extended. It saves the objects to the database. There are many other functions and goodies that come with Doctrine classes, we will see later in the tutorials.
You should see output:
added 2 users
- Now go back to phpMyAdmin: http://localhost/phpmyadmin/
- Browse the table ‘user’
Voila! Now you should be able see the 2 new records that just got created.

Stay Tuned
We just saw how to install and setup CodeIgniter with Doctrine. It took some work, but now we have a powerful MVC framework and ORM combination.
In the next tutorials, I will show you more practical examples and eventually build a functional website. You will see how easy it is to create models with Doctrine and save time from having to write repetitive CRUD (Create, read, update and delete) functions in all of your models.
Doctrine will also help us handle the relationships between our classes, and let us avoid writing complex logic code and queries.
See you next time!

Pingback: Tweets that mention CodeIgniter and Doctrine from scratch.Day 1 – Install and Setup. | PHP and Stuff -- Topsy.com
#1 by David Ferguson on October 29th, 2009
| Quote
Any plans to turn these into screencasts? I am tempted to read it but honestly, I really hate sitting here reading through something this long. Chances are I typically know most of it, but then I try to skim over the stuff and I’ll miss one little thing that was important
I’m lazy, what can I say? haha
#2 by Burak on October 29th, 2009
| Quote
Yea, I am planning on doing some screencasts in the near future. But I don’t think they can replace the article format entirely.
#3 by DANIEL BRAHM on October 29th, 2009
| Quote
I have been working with CI for 2 years and I am always checking for more about ci. Keep your great job!
#4 by kodegeek on October 29th, 2009
| Quote
Hi, i’ve followed every steps as above, in Mac with php 5.2.6 and mysql 5.0.41 using MAMP, if i hit the worl method – it shows fine but if i hit for test user, nothing comes – just a blank page! I realy like your post that implements ORM feature. Here are the error log i found(which seems no error)
DEBUG – 2009-10-30 06:04:19 –> Config Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Hooks Class Initialized
DEBUG – 2009-10-30 06:04:19 –> URI Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Router Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Output Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Input Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Global POST and COOKIE data sanitized
DEBUG – 2009-10-30 06:04:19 –> Language Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Loader Class Initialized
DEBUG – 2009-10-30 06:04:19 –> Plugin loaded: doctrine_pi
DEBUG – 2009-10-30 06:04:19 –> Controller Class Initialized
Thanks
#5 by Burak on October 29th, 2009
| Quote
Try adding some echo statements inside the user_test() function. Both at the beginning and also between the lines.
See if you get any output at all.
Also I had a missing parenthesis at the end of the SQL query for generating the user table, I just fixed that.
#6 by Pierce on October 29th, 2009
| Quote
This is a great first look into Doctrine, which I have been interested in for some time. Great job
#7 by Aziz Light on October 30th, 2009
| Quote
Great job! I can’t wait for the next tutorials, and the eventual screencasts.
Also, I totally agree with you: as much as I love screencasts, a screencast can entirely replace a written article.
By the way I had a (weird) question. Since we’re using Doctrice to extend our models, can’t we remove all the Model class, database drivers, etc that we are not using anymore so that the whole app become smaller? or that might break CI?
#8 by Burak on October 30th, 2009
| Quote
You can delete the entire database folder if you want. But I believe CodeIgniter doesn’t load the database libraries unless you ask it to. So we’re already saving memory and execution time by not loading them.
Model is a very small component, but if you really want to remove it, first you need to delete this line in doctrine_pi.php:
require_once BASEPATH.’/libraries/Model.php’;
#9 by Aziz Light on October 30th, 2009
| Quote
Yeah obviously if I use doctrine I won’t autoload the database library (which I do normally). My point is to save space, but since the database folder is indeed very small it’s not worth it.
By the way, I absolutely love how you designed your comments display, with the thumbnail of the author’s site and the Reply | Quote links appearing on hover.
Actually, the whole design of the site is really cool. Good Job!
#10 by Kyle Farris on October 30th, 2009
| Quote
I second Aziz… this was very informative. I’ve always been very interested in trying Doctrine in Codeigniter but was never motivated enough to sit down and figure it out. It’s nice when people do that for you (and do it well).
Can’t wait for the tutorial/screencasts. My two cents: If every tutorial was written, I wouldn’t care… I’d read them all… it’s the content that matters to me, not the medium of delivery.
Once again, great job.
#11 by Rafael F P Viana on October 31st, 2009
| Quote
Very nice walkthrough, its on my delicious allready.
Great job!
Trackback: MVCForge - News for MVC Web Developers
#12 by iDVB on November 3rd, 2009
| Quote
Nice Tut Burak! Wish I had this when I first got started!
Got a question for you that you might have solved regarding this plugin.
Can you (or anyone) have a peak at this?
http://codeigniter.com/forums/viewreply/659878/
I feel like I have a good handle on everything doctrine except this issue.
Cheers!
#13 by Burak on November 3rd, 2009
| Quote
The link to the plugin in that article is broken, so I can’t take a look at the code.
However, from what I understand, Doctrine is just passing you an error from MySQL regarding a foreign key violation issue.
Is it trying to drop the tables one by one, or is just calling Doctrine::dropDatabases(); ?
#14 by iDVB on November 3rd, 2009
| Quote
My apologies…I thought you were using this same plugin in this tut. s this not the case? I see you have doctrine setup as a “plugin” and that other url I gave was the first time I had seen it bootstrapped this way.
If your way is indeed setup differently…then can I ask….are YOU able to use Doctrine::dropDatabases(); even when there are FKs without getting errors?
The plugin I mentioned simply did this:
function doctrine_destroy_database() {
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$models = Doctrine::getLoadedModels();
foreach($models as $model) { $conn->export->dropTable(Doctrine::getTable($model)->getTableName());
}
}
#15 by Burak on November 3rd, 2009
| Quote
No I’m not using that one. Can you e-mail it to me? programming[AT]gmail.com
Doctrine::dropDatabases() should work. You might also need to call Doctrine::createDatabases() before creating tables.
But be careful with it, because it will drop the entire database, so if there are non-Doctrine tables, they will be dropped too.
#16 by Bradigan on November 3rd, 2009
| Quote
Great tutorial! Just found it on Google today.
I have the exact same problem as KodgGeek above. Same Debug (no errors). I’m also on a Mac running PHP / Mysql.
I did as you mentioned and put several echo statements at the beginning, middle and end of the user_test function, but still nothing.
#17 by Burak on November 3rd, 2009
| Quote
There might be some hidden errors going on. I don’t have a Mac currently to test this.
Maybe error reporting in MAMP is off by default?
Found this article on turning them on: http://www.jhuskisson.com/code-tidbits/re-enabling-error-reporting-in-mamp
#18 by Bradigan on November 3rd, 2009
| Quote
Great Suggestion. However I still received a blank page. BUT, I did manage to find this:
and it had the following error:
[03-Nov-2009 20:50:45] PHP Fatal error: Class ‘User’ not found in /Users/brad/Sites/mysite/application/controllers/hello.php on line 13
Like some other tutorials out there, I have moved the /application folder out of the /system folder. I put the folder back in there, but it still did not work.
#19 by Bradigan on November 3rd, 2009
| Quote
BTW, I had a missing ; in one of my lines and now I can get the echo statement at the top of user_test function, so I know its getting called now for sure. I’ll see if I can figure it out, I’ll post the answer here (hopefully)
#20 by Bradigan on November 3rd, 2009
| Quote
Fixed Blank Page Issue:
I had to move the /application/plugins/doctrine so it was in /system/plugins/doctrine
(Remember, I have the application folder out of my system folder).
I then had to move doctrine_pi.php folder to /system/plugins folder.
Lastly, I had to change the doctrine_pi.php file so that this line:
require_once APPPATH.’/plugins/doctrine/lib/Doctrine.php’;
was changed to
require_once BASEPATH.’/plugins/doctrine/lib/Doctrine.php’;
And now everything works!
Thanks AGAIN! Great Series!
#21 by Blue on January 18th, 2010
| Quote
Dear Bradigan,
I’m a very newby for Codeigniter. I’ve found your comments are very useful for me. I have a problem as below:
Fatal error: Class ‘User’ not found in C:\AppServ\www\CodeIgniter\system\application\controllers\hello.php on line 13
I tryed to solve it by following your guide, I moved the doctrine folder into /system/plugins and changed require_once APPPATH.’/plugins/doctrine/lib/Doctrine.php’; to require_once BASEPATH.’/plugins/doctrine/lib/Doctrine.php’;, but it’s still show the same error. Could you please give me any advice?
PS. very sorry for my English ^^
Pingback: » Les liens de millieu de semaine ! oxynel, blog communication - Agence de communication Montpellier
Pingback: CodeIgniter, ORM, Doctrine | PHP - TechnoFrame
#22 by iDVB on November 9th, 2009
| Quote
Does anyone have any links for good examples, tuts or the like that relate to CodeIgniter, Doctrine and OOP?
Thanks to help from Burak and a few others, I’ve managed to get this implementation combination working 100%. However, could really use some guidance on how Doctrine and CI play in the big picture.
Eg. Let’s say I want to build a website that can have many users and groups with various permissions. As far as security/permissions I would have a Doctrine User Class with function setpassword() would should hash the password. For extensibility, I’d like that actual “hashing” to be done in some kinda external CodeIgniter model called lets say…Auth_model->hashpassword()
Could you/Should you access the CI “Auth_model->hashpassword()” from within the Doctrine “User-setpassword()” function?
I know this is a crap example….but I’m really just trying to wrap my head around these fine ladies. (CI & Doctrine)
Cheers
#23 by Burak on November 9th, 2009
| Quote
It shouldn’t be a model in my opinion, if it’s just for utility. Models are meant to represent data. You can create a helper or library instead.
#24 by iDVB on November 9th, 2009
| Quote
Oh right, however, I’m more concerned with the Doctrine CI part of that example then anything….eg….even as a helper or library…Could you/should you being using a “CI” helper/library from “within” a Doctrine Class (User Class). What would that look like? as I assume you would have to load in the CI classes using “require_once” or something of the like? Reason being that, is it not true, that CI classes are not accessible (for free) from within Doctrine Classes?
Hope some of that makes some sense.
#25 by Burak on November 9th, 2009
| Quote
You need to get the CI superclass, since you can’t do $this->load
$CI =& get_instance();
$CI->load->helper(’blahblah’);
#26 by iDVB on November 9th, 2009
| Quote
Right…sorry…I did read that before. Is that the proper/efficient thing to do with CI and Doctrine? Eg. If I have a Doctrine User Class that loads that helper….would that not mean that for each time a User Object gets created…that helper will get loaded again and again? Something about this just seem like it might possibly be inefficient? Of course, I’m sure you have a much better handle on it then I, but I had to ask.
#27 by Burak on November 9th, 2009
| Quote
CI knows that a helper is already loaded. When load() is called again on the same helper, it doesn’t actually load anything. Helpers exist globally once loaded, because they are just procedural functions.
And the get_instace() call only gets a “reference” to an object, that already exists. It doesn’t get recreated or reloaded.
I believe it’s an efficient way of accessing/calling CI stuff from within a Doctrine Model.
If you really wanted to get deep into the “best practices” regarding OOP, some people would probably rather use the “Dependency Injection” pattern or something similar. But even CI itself does not follow that convention. I wouldn’t worry too much about it.
#28 by iDVB on November 9th, 2009
| Quote
Thanks again Burak. I’ll paste something useful once I’ve got a bit more into this.
Cheers
#29 by AD on November 10th, 2009
| Quote
One question you have not addressed — Why should we bother adding doctine? What’s wrong with using CodeIgniter as it is? What problem are you addressing and why should I, as a developer, care?
Thanks.
#30 by Burak on November 10th, 2009
| Quote
What do you mean I have not addressed it? The very first section of the article is titled “Why add Doctrine to CodeIgniter?”.
Codeigniter doesn’t have an ORM, it just has the Active Record class, which has limited functionality.
#31 by Kerran on November 11th, 2009
| Quote
awesome tutorial dude, keep up the good work and I look forward to creating this website with you
#32 by walter on November 24th, 2009
| Quote
Great tutorial, keep it going!
Lot of people are googling for ci tutorials nowdays.
Pingback: CodeIgniter – Doctrine ORM Tutorial : A way of enhancing CI « IndiRelease
Pingback: PHP MVC Tutorial series - OSNN Forum
Pingback: CodeIgniter et Doctrine à partir de zéro. Jour 1 – L’installation « Lerni – Le blog du site
#33 by Bruno on November 30th, 2009
| Quote
Really nice tuts, mate. Thanks to share!
Pingback: Обзор e-$ и прочего говна » Blog Archive » 21 Совет по оптимизации MySQL
#34 by Budy on December 3rd, 2009
| Quote
Really a great tutorial, very appreciate it. Thanks for your sharing, Burak
#35 by Sander Versluys on December 4th, 2009
| Quote
Awesome tutorial, i’ve been using CI and Doctrine in a similar way… It’s always nice to see how others did it! Thanks!
#36 by Enrique on December 8th, 2009
| Quote
Awesome tutorial. AWESEOME !!
I didn’t know about Doctrine at all, just heard of it someday…
Thanks !!
#37 by Taylan Bahar on December 9th, 2009
| Quote
Benim iki sorum olacak.
Birincisi : Neden codeigniter? Neden tanıdığım web programcıları codeigniter’ı kötülüyor?
İkincisi : bu alıştırmaların Türkçe’sini yayınlamayı düşünüyor musun?
#38 by mehike on December 12th, 2009
| Quote
excuse me for bad english… but my question:
In one computer in Windows XP system all works fine: Xampp+Codeigniter+Doctrine.
same, but in Linux (lampp+CodeIgniter+Doctrine) I can’t connect mysql with Doctrine (CodeIgniter with models and mysql works fine, connected to mysql) – but If I want use Doctrine in my web page:
A PHP Error was encountered
Severity: Warning
Message: PDO::__construct() [pdo.--construct]: [2002] Invalid argument (trying to connect via unix://)
Filename: Doctrine/Connection.php
Line Number: 474
Fatal error: Uncaught exception ‘Doctrine_Connection_Exception’ with message ‘PDO Connection Error: SQLSTATE[HY000] [2002] Invalid argument’ in /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Connection.php:478 Stack trace: #0 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Connection/Mysql.php(101): Doctrine_Connection->connect() #1 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Transaction.php(186): Doctrine_Connection_Mysql->connect() #2 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Connection.php(1376): Doctrine_Transaction->beginTransaction(NULL) #3 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Export.php(1210): Doctrine_Connection->beginTransaction() #4 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Export.php(1100): Doctrine_Export->exportClasses(Array) #5 /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Core.php(889): Doctrine_Export->exportSchema(NULL) #6 /opt/lampp/htdocs/uusw in /opt/lampp/htdocs/uusweb/application/plugins/doctrine/lib/Doctrine/Connection.php on line 478
in database.php:
$db['default']['hostname'] = “localhost”;
$db['default']['username'] = “rp_user_27″;
$db['default']['password'] = “76rp77FG5er”;
$db['default']['database'] = “rpDB_uusweb_27″;
$db['default']['dbdriver'] = “mysql”;
$db['default']['dbprefix'] = “”;
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = “”;
$db['default']['char_set'] = “utf8″;
$db['default']['dbcollat'] = “utf8_unicode_ci”;
in doctrine_pi.php I print dsn string, it’s fine:
mysql://rp_user_27:76rp77FG5er@localhost/rpDB_uusweb_27
in doctrine Connection.php I print values too, before new PDO() command in 473line:
echo $this->options['dsn'].’*';
echo $this->options['username'].’*';
echo $this->options['password'].’*';
I see all fine:
mysql:host=localhost;dbname=rpDB_uusweb_27*rp_user_27*76rp77FG5er*
from linux commandline I can connect to mysql fine… I can’t think, that else I can do?
any help?
#39 by mehike on December 12th, 2009
| Quote
ok I’m find answer: unix_socket in connection string must be:
$dsn = $db[$connection_name]['dbdriver'] .
‘://’ . $db[$connection_name]['username'] .
‘:’ . $db[$connection_name]['password'].
‘@’ . $db[$connection_name]['hostname'] .
‘/’ . $db[$connection_name]['database'] .
‘;unix_socket=/opt/lampp/var/mysql/mysql.sock’;
#40 by Fabiano on December 19th, 2009
| Quote
PHP Error was encountered
Severity: Warning
Message: Cannot modify header information – headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/ci/system/application/config/autoload.php:1)
Filename: codeigniter/Common.php
Line Number: 360
An Error Was Encountered
Unable to load the requested file: plugins/doctrine_pi.php
What’s this? How I fix it?
#41 by Ale on December 20th, 2009
| Quote
Thanks dude…very great things!!!
#42 by joe on December 21st, 2009
| Quote
hi,
I was thinking about using an ORM for my projects and thank God you have done this piece. I have a question though, I followed the install just like you said copied the doctrine_pi.php and saved it in the specified folders but it gives me this error when I followed the first example you gave:
Fatal error: Uncaught exception 'Doctrine_Connection_Mysql_Exception' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inventory.user' doesn't exist' in D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection.php:1084 Stack trace: #0 D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection\Statement.php(253): Doctrine_Connection->rethrowException(Object(PDOException), Object(Doctrine_Connection_Statement)) #1 D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection.php(1049): Doctrine_Connection_Statement->execute(Array) #2 D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection.php(693): Doctrine_Connection->exec('INSERT INTO use...', Array) #3 D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection\UnitOfWork.php(595): Doctrine_Connection->insert(Object(Doctrine_Table), Array) #4 D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection\Unit in D:\xampplite\htdocs\inventory\application\plugins\doctrine\lib\Doctrine\Connection.php on line 108I am using xampplite 1.7.2 thanks for all the good work. will expect to hear from you soon.
#43 by Burak on December 21st, 2009
| Quote
It says the table “inventory.user” does not exist. You need to create it first, as described in the article.
#44 by joe on December 21st, 2009
| Quote
you know what I am sooooo sorry for this. I missed an ’s’ at the end of user. when I got your reply was when i noticed the missing s. I am so sorry.
Cheers
#45 by Tim Reynolds on December 26th, 2009
| Quote
This is a great tutorial. Have never heard of doctrine before, but I definitely intend on following these tuts.
It might be a nice idea to move the application folder outside the systems folder to allow CI to be easily updated. I would also change the name of the application and systems folder for security.
#46 by lechuzo on December 27th, 2009
| Quote
Hi to everyone.
I have this error when I’m trying to run the Day1 tutorial.
I’m working on XP and I have Appserv 2.5.9 with PHP Version 5.2.3, phpMyAdmin Version 2.10.2 and mysql Version 5.0.45-community-nt-log
Could you have an ida about this message? I will really appreciate your help. (Sorry about my English)
Fatal error: Uncaught exception ‘Doctrine_Transaction_Exception’ with message ‘Rollback failed. There is no active transaction.’ in C:\AppServ\www\ci_doctrine_day1\system\application\plugins\doctrine\lib\Doctrine\Transaction.php:319 Stack trace: #0 C:\AppServ\www\ci_doctrine_day1\system\application\plugins\doctrine\lib\Doctrine\Connection.php(1426): Doctrine_Transaction->rollback(NULL) #1 C:\AppServ\www\ci_doctrine_day1\system\application\plugins\doctrine\lib\Doctrine\Connection\UnitOfWork.php(136): Doctrine_Connection->rollback() #2 C:\AppServ\www\ci_doctrine_day1\system\application\plugins\doctrine\lib\Doctrine\Record.php(1597): Doctrine_Connection_UnitOfWork->saveGraph(Object(User)) #3 C:\AppServ\www\ci_doctrine_day1\system\application\controllers\hello.php(16): Doctrine_Record->save() #4 [internal function]: Hello->user_test() #5 C:\AppServ\www\ci_doctrine_day1\system\codeigniter\CodeIgniter.php(236): call_user_func_array(Array, Array) #6 C:\AppServ\www\ci_doctrine_day1\index.php(115): require_once(’C:\AppServ\www\… in C:\AppServ\www\ci_doctrine_day1\system\application\plugins\doctrine\lib\Doctrine\Transaction.php on line 319
#47 by Burak on December 27th, 2009
| Quote
Look at my comment here about Appserv: http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login/comment-page-1#comment-303
See if that solves your issue.
#48 by lechuzo on December 29th, 2009
| Quote
Thanks a lot!!! I’m sorry about my hurry. When I read this link everything went right. I’m still learning with your tutorial.
Pingback: Чуть более 20 хороших советов по MySQL (часть 2) » Пара слов о программировании
#49 by Максим on December 31st, 2009
| Quote
Занятная статья, да и сам сайт я смотрю очень даже не плох. Попал сюда по поиску из Гугла, занес в закладки
#50 by Naim on January 2nd, 2010
| Quote
Would you be soo Kind to show us how to install Doctrine with Kohana please. If you have used at all?
Thanks
#51 by Кирилл Александров on January 5th, 2010
| Quote
Действительно интересно написанно, я наверное бы так не смог.
Pingback: CodeIgniter Clan Site – Part 1 | PHP Tutorials
#52 by Blue on January 19th, 2010
| Quote
hi All,
I’m a very newby for CodeIgniter. Now, I’m trying to do Web Application Project using Codeigniter. I’ve tried to follow Day 1 – Install and Setup. I faced the problem below:
Fatal error: Uncaught exception ‘Doctrine_Connection_Exception’ with message ‘Couldn’t locate driver named mssql’ in C:\AppServ\www\ci\system\plugins\doctrine\lib\Doctrine\Connection.php:486 Stack trace: #0 C:\AppServ\www\ci\system\plugins\doctrine\lib\Doctrine\Connection\UnitOfWork.php(54): Doctrine_Connection->connect() #1 C:\AppServ\www\ci\system\plugins\doctrine\lib\Doctrine\Record.php(1691): Doctrine_Connection_UnitOfWork->saveGraph(Object(Users)) #2 C:\AppServ\www\ci\system\application\controllers\hello.php(17): Doctrine_Record->save() #3 [internal function]: Hello->user_test() #4 C:\AppServ\www\ci\system\codeigniter\CodeIgniter.php(232): call_user_func_array(Array, Array) #5 C:\AppServ\www\ci\index.php(115): require_once(’C:\AppServ\www\…’) #6 {main} thrown in C:\AppServ\www\ci\system\plugins\doctrine\lib\Doctrine\Connection.php on line 486
I use :
- Apache Web Server version 2.2.8
- PHP Script Language version 5.2.6
- Microsoft SQL server
Could you please help me solve this problem?
Thank you very much. ^^
#53 by Burak on January 20th, 2010
| Quote
You need to make sure the MsSQL driver is enabled with PDO.
#54 by Asakurayoh on January 19th, 2010
| Quote
Hi.
I just can get this work. I use Doctrine 1.2 and the autoload doesn’t seem to work.
(Don’t find my Model, and if I include the model (with include), it doesn’t find Doctrine_Record……..)
Do you have an idea how to do?
I’m on Wampserver on Windows XP.
Thanks.
#55 by Burak on January 20th, 2010
| Quote
I am not sure. Try downloading the zip file provided at the beginning of the article.
#56 by Joakim Kejser on January 20th, 2010
| Quote
Hi Burak.
I really like the combination of codeigniter and doctrine, thank you very much for the article. It’s by far the slickest implementation of doctrine in codeigniter i’ve seen.
I just have a single question, why bother loading the CI models library from the doctrine plugin?
#57 by Burak on January 20th, 2010
| Quote
When I had a model that was extending the CI Model class, i was getting errors. Some people might be using both CI Model’s and Doctrine Model’s at the same time, that’s why I included that.
Later I found a way around it actually. Just need to add one more Doctrine autoloader just for models (which is actually lacking from the official documentation for some reason), and set the loading to conservative (it’s aggressive by default so it loads all models).
#58 by Patrick Fraley on January 23rd, 2010
| Quote
Moin Burak,
Is it also possible to install the doctrine into the system/plugins folder? I have my server setup to have a single CodeIgniter installation to be used by multiple virtual hosts/applications and I would like to have doctrine available in all those apps without having an installation of doctrine in all of them (hard to maintain)?
#59 by Patrick Fraley on January 23rd, 2010
| Quote
Sorry I noticed someone did that already, made the changes to the doctrine_ci.php (line 5 changed APPPATH to BASEPATH). Will test later if it still works
thanx for posting these cool tutorials
#60 by jävi on January 26th, 2010
| Quote
Hi Burak,
Firstly, really great tutorial, thank you!.
Just one question. What about generation the models from the DB with Doctrine? I mean this:
Doctrine_Core::generateModelsFromDb(’models’, array(’doctrine’), array(’generateTableClasses’ => true));
I tried to do it but nothings happens, no errors and no models anywhere.
Can you figure out why?
Thank you!
#61 by Burak on January 29th, 2010
| Quote
The first parameter should be the path to the models folder, which should be this:
APPPATH.’/models’
and the folder should probably be writable too
but I don’t understand why it didn’t give you an error.
#62 by swapnil on January 27th, 2010
| Quote
tanx dude for the step by step illustrations…wonderful article…tanx a ton…!!!
#63 by a.k.d. on January 31st, 2010
| Quote
thanks for your great tutorial !!
helped me a lot
however, in case using Doctrine 1.2, our plug-in must have
spl_autoload_register(array(’Doctrine’, ‘modelsAutoload’));
Otherwise models would not be auto-loaded, end up to ‘Class not found’ error.
Bottom entry of
http://www.doctrine-project.org/upgrade/1_2
“Models Autoloading”
seems to be it.
Unfortunately, this is not mentioned in official 1.2 documentation and I’ve spent almost 2 days.
(esp. http://www.doctrine-project.org/documentation/manual/1_2/en/introduction-to-models#autoloading-models)
hope this helps.
//
#64 by Burak on February 2nd, 2010
| Quote
I found out about this later too. But in the plugin file in this article, there is a call to the loadModels function, which will load all the model files, so you won’t get that class not found error.
You need to register modelsAutoload only when using conservative loading.
Also I found out that it doesn’t work very well when you have base classes, table classes etc.. in sub folders. The best solution might be writing a custom autoloader in that case, which is not difficult.
#65 by a.k.d. on February 3rd, 2010
| Quote
thanks for your reply.
well, let me explain what happend in my case.
I’m generating my models by invoking Doctrine_Cli, which seems to be convenient way to get model classes from YAML, without writing code
It generates model classes under APP_PATH/models and base classes under APP_PATH/models/generated.
e.g. APP_PATH/models/SimpleModel and APP_PATH/models/generated/BaseSimpleModel.
this means that generated/BaseSimpleModel.php must be loaded before loading SimpleModel.php.
However, Doctrine ‘require_once’ in aggressive mode, I get
–
Fatal error: Class ‘BaseSimpleModel’ not found in APP_PATH/models/SimpleModel.php on line 13
–
In this article, model is directly derived from Doctrine_Record and base class dependency doesn’t matter.
conservative mode and ‘modelsAutoload’ solved my problem, at least for me.
hope this helps.
thanks.
//
#66 by fpbosch on February 6th, 2010
| Quote
It drives me crazy. I tried It but I still have the same error I don’t know what can I do ? it doesn’t load my models. can you post your code of the doctrine_pi.php
#67 by a.k.d. on February 6th, 2010
| Quote
Hi.
fpbosch:
Are you using models generated by Doctrine 1.2.x in aggressive mode?
Have you tried modelsAutolod in conservative mode?
What error do you see?
Burak:
may I post whole 65 lines of modified doctrine_pi.php here for fpbosch?
thanks.
//
#68 by fpbosch on February 7th, 2010
| Quote
is it different generate models from aggressive or conservative ? I thought it was only different in the way of load it. In my doctrine_tools I created this function
public function create_models() {
Doctrine::generateModelsFromDb(APPPATH.’models’);
}
The problem is that when I call a class it doesn’t found it e.g:
Fatal error: Class ‘BaseLyProvinces’ not found in /var/www/lybica/application/models/LyProvinces.php on line 13
I don’t how to use modelsAutoload I tried this
spl_autoload_register(array(’Doctrine’, ‘modelsAutoload’));
// we load our database connections into Doctrine_Manager
// this loop allows us to use multiple connections later on
foreach ($db as $connection_name => $db_values) {
// first we must convert to dsn format
$dsn = $db[$connection_name]['dbdriver'] .
‘://’ . $db[$connection_name]['username'] .
‘:’ . $db[$connection_name]['password'].
‘@’ . $db[$connection_name]['hostname'] .
‘/’ . $db[$connection_name]['database'];
Doctrine_Manager::connection($dsn,$connection_name);
}
But then I get this error:
Fatal error: Class ‘Doctrine_Manager’ not found in /var/www/lybica/application/plugins/doctrine_pi.php on line 24
I would like to see you code
Thank you a lot
#69 by fpbosch on February 7th, 2010
| Quote
ooops I’ve got it
spl_autoload_register(array(’Doctrine’, ‘autoload’));
spl_autoload_register(array(’Doctrine_Core’, ‘modelsAutoload’));
// we load our database connections into Doctrine_Manager
// this loop allows us to use multiple connections later on
foreach ($db as $connection_name => $db_values) {
// first we must convert to dsn format
$dsn = $db[$connection_name]['dbdriver'] .
‘://’ . $db[$connection_name]['username'] .
‘:’ . $db[$connection_name]['password'].
‘@’ . $db[$connection_name]['hostname'] .
‘/’ . $db[$connection_name]['database'];
Doctrine_Manager::connection($dsn,$connection_name);
}
// CodeIgniter’s Model class needs to be loaded
require_once BASEPATH.’/libraries/Model.php’;
// telling Doctrine where our models are located
Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
Doctrine::loadModels(APPPATH.’/models’);
.
.
…
Thank you!
#70 by fpbosch on February 7th, 2010
| Quote
But now it doesn’t found the Current_User class…
Fatal error: Class ‘Current_User’ not found in /var/www/lybica/application/controllers/login.php on line 65
#71 by a.k.d. on February 8th, 2010
| Quote
Do you have Current_User.php in your APPPATH/models/ directory?
In conservative mode, Doctrine assumes that file name == class name.
i.e. You need to define Current_User class in APPPATH/models/Current_User.php, otherwise it won’t get autoloaded.
thanks.
//
#72 by Firman Nugraha on February 2nd, 2010
| Quote
Hello Mr. Burak, I just finished reading and practicing this tuturial. I’m heavily impressed with the way of how you write the tutorial and how you create the examples.
If possible, can I translate your tutorial to my native language which is Indonesian and post it in my blog? And of course with crediting you. I believe this will help my fellow Indonesian developers who don’t have much skill in English.
#73 by Burak on February 2nd, 2010
| Quote
Yes, you may do that
#74 by Jesse Schutt on February 3rd, 2010
| Quote
Hello Burak
Thanks for walking us through this process!
I’m getting an error that I was hoping you could help with. When I load http://localhost:8888/ci_doctrine_day_1 I get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: root
Filename: plugins/doctrine_pi.php
Line Number: 17
A PHP Error was encountered
Severity: Notice
Message: Undefined index: root
Filename: plugins/doctrine_pi.php
Line Number: 18
A PHP Error was encountered
Severity: Notice
Message: Undefined index: localhost
Filename: plugins/doctrine_pi.php
Line Number: 19
A PHP Error was encountered
Severity: Notice
Message: Undefined index: ci_doctrine
Filename: plugins/doctrine_pi.php
Line Number: 20
When I try to load the hello/world or the hello/user_test, I just get a blank page. Any ideas?
Thanks again!
#75 by Burak on February 6th, 2010
| Quote
I’m not sure. Something might be wrong with the $db array in your config/database.php file.
#76 by a.k.d. on February 8th, 2010
| Quote
Do you have Current_User.php in your APPPATH/models/ directory?
In conservative mode, Doctrine assumes that file name == class name.
i.e. You need to define Current_User class in APPPATH/models/Current_User.php, otherwise it won’t get autoloaded.
thanks.
//
#77 by a.k.d. on February 8th, 2010
| Quote
oops, sorry for this.
I see no ‘reply’ link to fpbosch’s replies …
//
#78 by Mark on February 11th, 2010
| Quote
So I’ve worked with Doctrine just a bit, and using their autogenerating methods, you get a the following file layout
Models
- generated (folder)
- – BaseCity.php (this extends the doctrine record class)
- city.php ( extends basecity )
All of the custom/override methods go in city.php and table definitions/relationships go into basecity.php. Curious where you would override methods add custom methods to your model. Would it be in the same model file?
#79 by Burak on February 13th, 2010
| Quote
The auto-generated city.php file is mostly blank right? I would put the custom methods there. So Basecity.php just remains for defining the table structure.
If you don’t want this separation, you can tell Doctrine to not generate base class files. There is an option for it.
#80 by Didin Wahyudin on February 14th, 2010
| Quote
i am using WAMP, when i tried your 1st tutorial, then i browse http://localhost/doctrine/index.php/hello/user_test, i getting this error:
Fatal error: Uncaught exception ‘Doctrine_Connection_Exception’ with message ‘PDO Connection Error: SQLSTATE[28000] [1045] Access denied for user ‘roor’@'localhost’ (using password: NO)’ in G:\web\doctrine\system\application\plugins\Doctrine\lib\Doctrine\Connection.php:474 Stack trace: #0 G:\web\doctrine\system\application\plugins\Doctrine\lib\Doctrine\Connection\Mysql.php(101): Doctrine_Connection->connect() #1 G:\web\doctrine\system\application\plugins\Doctrine\lib\Doctrine\Connection\UnitOfWork.php(54): Doctrine_Connection_Mysql->connect() #2 G:\web\doctrine\system\application\plugins\Doctrine\lib\Doctrine\Record.php(1691): Doctrine_Connection_UnitOfWork->saveGraph(Object(User)) #3 G:\web\doctrine\system\application\controllers\hello.php(17): Doctrine_Record->save() #4 [internal function]: Hello->user_test() #5 G:\web\doctrine\system\codeigniter\CodeIgniter.php(236): call_user_func_array(Array, Array) #6 G:\web\doctrine\index.php(115): require_once(’G:\web\doctrine…’) #7 {main} thrown in G:\web\doctrine\system\application\plugins\Doctrine\lib\Doctrine\Connection.php on line 474
how to resolve this problem. Sorry, bad english.
#81 by Burak on February 15th, 2010
| Quote
Did you put “roor” for the database username instead of “root” ?
#82 by Didin Wahyudin on February 16th, 2010
| Quote
oo.. i see, thank you. Sorry for my idiot.
#83 by Dirk Franssen on February 16th, 2010
| Quote
Great series!
I have a doctrine class A extends B.
But I get a Fatal error: Class ‘B’ not found in … A.php
How to make sure B is also autoloaded while A gets autoloaded?
Thanks in advance
#84 by Dirk Franssen on February 16th, 2010
| Quote
Found it. These changes are working for me:
spl_autoload_register(array(’Doctrine’, ‘autoload’));
spl_autoload_register(array(’Doctrine’, ‘modelsAutoload’));
Doctrine_Core::setModelsDirectory(APPPATH.’/models’); //instead of loadModels
Doctrine_Manager::getInstance()->setAttribute(’model_loading’, ‘aggressive’);
#85 by Ned on February 16th, 2010
| Quote
Hi,
i have a problem.
In page :
http://localhost/ci_doctrine_day1/index.php/hello/world
i get a message:
Unable to load the requested file: plugins/doctrine_pi.php
What can i solve this problem?
Thanks in advance.
#86 by Habib BULUT on February 18th, 2010
| Quote
Burak ellerine saglik kardesim :] cok kaliteli bir dokuman
Pingback: CodeIgniter- Doctrine ORM Tutorial: A way of enhancing CI | TheUnical Technologies Blog
#87 by zeeshaan on March 9th, 2010
| Quote
Fatal error: Uncaught exception ‘Doctrine_Connection_Mysql_Exception’ with message ‘SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘ci_doctrine.user_model’ doesn’t exist’ in C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection.php:1082 Stack trace: #0 C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection\Statement.php(269): Doctrine_Connection->rethrowException(Object(PDOException), Object(Doctrine_Connection_Statement)) #1 C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection.php(1042): Doctrine_Connection_Statement->execute(Array) #2 C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection.php(687): Doctrine_Connection->exec(’INSERT INTO use…’, Array) #3 C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection\UnitOfWork.php(631): Doctrine_Connection->insert(Object(Doctrine_Table), Array) #4 C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection\UnitOfWork.php(562): Doctrine_Connecti in C:\xampp\htdocs\system\application\plugins\doctrine\lib\Doctrine\Connection.php on line 1082 –
error -pls help