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!

Trackback: Prvi bosansko-hercegovački forum za web dizajn i web razvoj...
#1 by John on April 6th, 2012
| Quote
I have these message when run: system/application/controllers/hello.php
Fatal error: Class ‘User’ not found in www/CI2_doctrine/ci2/application/controllers/hello.php on line 12
Obs. I use CodeIgniter2 and Doctrine last version unzipped in my /ci2/application/plugins/Doctrine/lib/
#2 by John on April 6th, 2012
| Quote
Type your comment here
I have same probblem
#3 by John on April 6th, 2012
| Quote
Please help me to resolve the same problem, I am using CI2 and lat Doctrine
My e-mail: iovidiutoma[at]gmail.com
#4 by Travis on April 8th, 2012
| Quote
I’m also having the same problem submitted by John. Could this tutorial please be updated? I’m very interested in using CI2 with Doctrine 2.xx but it’s difficult to get all the configuration set up. Thank you -Travis
#5 by Aaron on April 9th, 2012
| Quote
This is a great article in theory, but not in practice since it uses CI 1.something and the current version of CI is version 2.1.0… Any plans to update it in the near future?
#6 by yusnur on April 11th, 2012
| Quote
for now, i develop codeigniter n doctrine, with package bundle automated, so..if install codeigniter..also include doctrine..(cause i’m newbie)..the problem is..i’ve follow step that u explain, but something happens is =Doctrine_Transaction_Exception’ with message ‘Rollback failed. There is no active transaction=, maybe u can help, me..?, thanks
#7 by Junaid Ali on November 5th, 2012
| Quote
Brilliant Article… I am using CI for a year and am extremely happy with it and this ORM will definitely move things to the next-level.
And believe me I know the next level as I am also into ASP.net MVC4 + EntityFramework and LINQ.
I would just love to see something like LINQ in PHP.
#8 by Jose A Fernandez on November 30th, 2012
| Quote
Hi! I downloaded Doctrine but the new version (2.3.0) does not have the lib folder. Can you help me? What should I copy to my plugins folder? Thanks,
#9 by social on December 6th, 2012
| Quote
Very quickly this site will be famous among all blog viewers, due to
it’s nice articles or reviews
#10 by Web developers on December 14th, 2012
| Quote
For the reason that the admin of this web page is working, no hesitation very soon it will be well-known, due to its
quality contents.
#11 by google+ vs. facebook on December 14th, 2012
| Quote
Heya i am for the first time here. I came across this board and I find It truly useful &
it helped me out much. I hope to give something back and help others like you
helped me.
#12 by Tahir Ghori on December 17th, 2012
| Quote
Hi! I have also same problem the new version (2.3.0) does not have the lib folder. Can you help me? What should I copy to my plugins folder?
waiting for your reply as soon as posible
Thanks,
#13 by Tahir Ghori on December 18th, 2012
| Quote
hi when i create a two user it is not show me the added 2 users but the value is to be add into the database and show me this type of error :
A PHP Error was encountered
Severity: Notice
Message: Undefined index: core
Filename: libraries/Loader.php
Line Number: 976
Fatal error: Uncaught exception ‘Doctrine_Connection_Mysql_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘johndoe’ for key ‘username” in /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection.php:1084 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection/Statement.php(253): Doctrine_Connection->rethrowException(Object(PDOException), Object(Doctrine_Connection_Statement)) #1 /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection.php(1049): Doctrine_Connection_Statement->execute(Array) #2 /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection.php(693): Doctrine_Connection->exec(‘INSERT INTO use…’, Array) #3 /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection/UnitOfWork.php(595): Doctrine_Connection->ins in /Applications/XAMPP/xamppfiles/htdocs/one_day/system/application/plugins/doctrine/lib/Doctrine/Connection.php on line 1084
#14 by food for gout on January 22nd, 2013
| Quote
Hello! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My web site looks weird when viewing from my iphone 4. I’m trying to find a theme or plugin that might be able to correct this problem.
If you have any suggestions, please share. Many thanks!
#15 by Rafal on February 1st, 2013
| Quote
This message is for people who using new version Doctrine 2.3 watch video and later look here http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html
very simple
sry, for my lenguage
#16 by Rafal on February 1st, 2013
| Quote
also this link is useful http://www.doctrine-project.org/downloads/
#17 by Rafal on February 2nd, 2013
| Quote
You can look to my topics about problems http://stackoverflow.com/questions/14661064/save-error-in-codeigniter-and-doctrine-tutorial/14661285#14661285
#18 by warts genital effect on fetus on February 16th, 2013
| Quote
First off I want to say excellent blog! I had a quick question that I’d like to ask if you don’t mind.
I was interested to find out how you center yourself and clear your mind prior
to writing. I’ve had trouble clearing my mind in getting my ideas out. I truly do enjoy writing but it just seems like the first 10 to 15 minutes are wasted simply just trying to figure out how to begin. Any suggestions or tips? Kudos!
#19 by quality garden sheds belfast on February 23rd, 2013
| Quote
Thanks for the good writeup. It if truth be told was a entertainment account it.
Look complicated to more introduced agreeable from you! By
the way, how can we keep up a correspondence?
#20 by denver home health aid on February 26th, 2013
| Quote
It’s in fact very complex in this full of activity life to listen news on TV, thus I only use the web for that reason, and obtain the most recent news.
Pingback: MySQL Best Practices | Rapidesigners
#21 by clear on March 12th, 2013
| Quote
Thanks for finally writing about >CodeIgniter and Doctrine from scratchDay 1 – Install and Setup
| PHP and Stuff <Liked it!
#22 by http://fakehermeswallet.blogspot.com/ on March 26th, 2013
| Quote
Fashion for $4300.Marc Jacobs Olga bags in navy louis vuitton hlouis vuitton handbags replicabags replica cream $1,495, sale $1,046.50Michael Kors clutch $395, sale
Pingback: Doctrine 2.x CRUD | BlogoSfera
#23 by livejournal.com on April 4th, 2013
| Quote
Then it is important to apply general amount involving any medical cream like Clearasil on your own
face. Touching your chin frequently will transfer these
germs and dirt to the chin area which may result in acne on chin.
There are a wide range of self tanners to choose from at department stores, but
why not treat yourself to a spray tan at your nearest tanning
salon.
#24 by growth-flex on April 5th, 2013
| Quote
Thanks for finally writing about >CodeIgniter and Doctrine from scratchDay 1 – Install and Setup | PHP and Stuff <Loved it!
#25 by internet marketing on April 5th, 2013
| Quote
Running a successful small business hinges on effective market research, and these
days with the proliferation of the Internet and Web 2
#26 by fake oakley flak jacket on April 8th, 2013
| Quote
There are varied shades of http; www. replicaoakleysdiscount. com/ available nowadays along with being entirely your choice to find the glass shade you pick. If you can be having trouble visualizing these oversized eyewear, imagine Elvis Presley. Elvis wore the sunglasses this were popular during the actual late 70s and early 80s. fake oakley flak jacket http://www.sunglasses-soaho.org/fake-oakley-flak-jacket-p-19.html
#27 by Jones sabo as talked over inside this say on April 12th, 2013
| Quote
Some truly fantastic posts on this website , thankyou for contribution. Jones sabo as talked over inside this say http://www.ebizq.net/blogs/ebizq_forum/2012/07/what-part-of-your-personal-life-would-benefit-most-from-bpm.php#comments
#28 by 43643 on May 16th, 2013
| Quote
I’m a writer from Rowland, United States just forwarded this onto a colleague who was doing some sort of research on this. And she actually ordered me lunch just because I discovered it for her… lol. Actually, allow me to paraphrase this…. Thanks for the meal… But yeah, thanx for taking some time to discuss this issue here on your web site.
#29 by Sky Angebote on May 17th, 2013
| Quote
Hey just wanted to give you a quick heads up and let you know
a few of the pictures aren’t loading correctly. I’m
not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.
#30 by Billy on May 20th, 2013
| Quote
If you are going for best contents like me, only visit this web site
every day for the reason that it offers quality contents, thanks