In this episode:
- We do a quick fresh install of CodeIgniter and Doctrine, without going into details like last episode.
- Briefly go over some of the basic concepts of CodeIgniter and Doctrine.
- First we will review Controllers and Views in CodeIgniter.
- Then we will move on to Models using Doctrine. This is where things are going to get a little different, compared to other CodeIgniter tutorials out there.
- Finally we will preview a sample Doctrine Model and talk about what our main project is going to be.
"CodeIgniter and Doctrine from Scratch" Series:
Let’s get started and make sure we have a fresh CodeIgniter+Doctrine install ready for some code.
Fresh Quick CodeIgniter+Doctrine Install
Fresh Install Instructions:
(if you want to use your files from Day 1, skip to the next section instead)
- Have your PHP+MySQL web server ready. Recommended: WAMP (for Mac: MAMP)
- Download my CodeIgniter+Doctrine bundle (v1.0).
- Extract and put the ci_doctrine folder into your web folder.
- Create a database named ci_doctrine for our project.
- Make sure your database info is correct in: system/application/config/database.php.
- Make sure base_url is correct in: system/application/config/config.php.
- See if its working: http://localhost/ci_doctrine/.
Done!
If you already have the files from Day 1:
(if you used the fresh install from the section above, skip this)
- Rename or Copy your install folder to: ci_doctrine. (I decided to do this so we don’t keep changing our site url on every tutorial)
- Delete: system/application/models/user.php
- Delete: system/application/controllers/hello.php
- Drop table: user
- Edit: system/application/config/config.php
// in system/application/config/config.php $config['base_url'] = "http://localhost/ci_doctrine/";
CodeIgniter URL structure
Url’s in CodeIgniter can look like these:
This url invokes the controller class named “CONTROLLER_NAME”, and call it’s method (function) named “METHOD_NAME”:
http://localhost/ci_doctrine/index.php/CONTROLLER_NAME/METHOD_NAME
Same as before, except it calls a method named index() by default:
http://localhost/ci_doctrine/index.php/CONTROLLER_NAME
Same as before. This time, it passes a “VALUE” as an argument to the controller method:
http://localhost/ci_doctrine/index.php/CONTROLLER_NAME/METHOD_NAME/VALUE
The value can be a number or a string.
You can keep appending more values in the url for passing additional arguments.
For More Info: Passing uri segments
CodeIgniter MVC (Model – View – Controller)
Models
We are going to be using Doctrine Model’s, instead of CodeIgniter. I will explain it later in the tutorial.
If you still want to learn about CodeIgniter Models, read: CodeIgniter Models
Views
- Views are created under system/application/views, and are named like my_view.php
- They are the output templates. They can contain html, javascript and more.
- Views also usually contain inline PHP code. (to display messages, run loops etc…)
- Controllers typically load views for displaying output.
Official docs: CodeIgniter Views
Controllers
We already covered this in Day 1. Look for the section called “CodeIgniter Crash Course: Controllers”.
Controller and View together
Here is a sample View (system/application/views/my_view.php):
Some plain text.
<div>
You can use HTML.
</div>
<div>
Display variables passed from a controller: <br />
<?php echo $message; ?> <br />
<?php echo $another_message; ?>
</div>
You can even do loops: <br />
<?php for ($i = 0; $i < 3; $i++) {
echo "Counter shows: $i <br />";
} ?>
Or in alternate syntax: <br />
<?php for ($i = 0; $i < 3; $i++): ?>
Counter shows: <?php echo $i; ?> <br />
<?php endfor; ?>
Here is a sample Controller (system/application/controllers/sample_controller.php), that loads a view:
class Sample_controller extends Controller {
function index() {
$data = array();
$data['message'] = "index was called";
$data['another_message'] = "blah blah";
$this->load->view('my_view',$data);
}
}
Both of these url’s will work:
http://localhost/ci_doctrine/index.php/sample_controller/index http://localhost/ci_doctrine/index.php/sample_controller
Browser would display:
Some plain text. You can use HTML. Display variables passed from a controller: index was called blah blah You can even do loops: Counter shows: 0 Counter shows: 1 Counter shows: 2 Or in alternate syntax: Counter shows: 0 Counter shows: 1 Counter shows: 2
Note:
- View contains a combination of raw output and simple inline PHP.
- index() is the default Controller function, so we don’t have to put it in the url.
- $this->load->view(’my_view’,$data) loads the view and outputs it to the browser.
- First argument ‘my_view’ is the name of the view file, without the .php part.
- Second argument $data is an array, which passes variables to the view.
- Example: $data['message'] becomes $message, and $data['another_message'] becomes $another_message, in our view.
(If you created the files above, to test the code, you can delete them now. We’re not going to use them again in our project.)
Doctrine Models
Models are classes that represent data (typically from your database).
For example, you might have a user table. So we can build a Model Class named “User” to represent the records in that table.
Our Model class should be able to peform CRUD (Create, Read, Update and Delete) operations. Luckily, Doctrine will be a great help in accomplishing this with minimal and clean code.
Differences in Usage (compared to CodeIgniter Models)
- They extend the Doctrine_Record class (instead of the “Model” class).
- They can be loaded like this: $u = new User(); (instead of this: $u = $this->load->model(’user’);)
thanks to the Doctrine autoload we registered in our plugin. - It is not PHP4 compatible.
That is all you need to know for now. It should be an easy transition for those of you already working with CodeIgniter.
What does a Doctrine Model look like?
Here is a little PREVIEW of the kind of Model’s we are going to be building. We’ll get into more details in the next tutorials.
<?php
class User extends Doctrine_Record
{
// define table columns in this function
public function setTableDefinition() {
$this->hasColumn('username', 'string', 255);
$this->hasColumn('password', 'string', 255);
$this->hasColumn('email', 'string', 255, array(
'email' => true // It can validate e-mail input
));
// supports many column types, including enum
$this->hasColumn('status', 'enum', null,
array('values' => array('unverified', 'verified', 'disabled'))
);
$this->hasColumn('referer_id', 'integer', 4);
}
// setup some options
public function setUp() {
// creates a relationship with a model named Post
$this->hasMany('Post as Posts', array(
'local' => 'id',
'foreign' => 'post_id'
));
// can even have a relationship with itself
$this->hasOne('User as Referer', array(
'local' => 'referer_id',
'foreign' => 'id'
));
// causes 'created_at' and 'updated_at' fields to be updated automatically
$this->actAs('Timestampable');
// password field gets a mutator assigned, for automatic encryption
$this->hasMutator('password', 'md5Password');
}
// a mutator function
public function md5Password($value) {
$this->_set('password', md5($value));
}
}
Once we create Doctrine Model’s like this, we can do all kinds of database operations. Doctrine can even create the table based on the model information alone.
Also keep in mind that there are other ways of creating Doctrine Models, such as using schema files. But we will not get into that until later.
Stay Tuned
In the next episode, we will start building a project, which will be a Message Board and possibly more… This is a great candidate for a tutorial project with Doctrine because of all the different relationships involved between models such as: users, posts, threads, forums, groups, attachments etc…
See you next time!
#1 by hamochi on October 31st, 2009
| Quote
This is really good stuff, looking forward to your next post =)
#2 by zack on November 1st, 2009
| Quote
So.. Why did we delete stuff, if we didn’t build anything this time.
Maybe next time?
#3 by Burak on November 1st, 2009
| Quote
Just wanted to have a clean install ready for our project. And yeah, we will be building stuff finally
, I’m working the 3rd article.
#4 by zack on November 1st, 2009
| Quote
I was just giving ya a hard time
I’m loving the series. I’m a HUGE CI supporter, and really been getting tired of build CRUD. I knew doctrine was the answer, but just never took the time to learn it.
You have a donate button?
#5 by Burak on November 1st, 2009
| Quote
Now I do
thanks for the reminder
#6 by zack on November 1st, 2009
| Quote
I’ll be sure to donate after the next tutorial.. Just wanna make sure they keep coming
#7 by Kyle Farris on November 2nd, 2009
| Quote
Doctrine really seems like the way to go. I’m actually considering puttingmy current project on pause until I can get a better idea of how Doctrine works. Seems like it might end up saving time even with the temporary sojourn. Keep’em coming. And, like Zack, if the quality tutorials keep coming, expect a donation.
#8 by Tutorials on November 4th, 2009
| Quote
I found your site on a tutorial directory. We recently launched tutorialgrad.com. It’s similar to those other tutorial sites only easier for you. All you have to do is submit your RSS Feed once, we do the rest. We will check your feed for tutorials and post them daily, all with direct links to your site (we don’t frame your content). If you are interested please check it out and let us know what you think.
#9 by cell on December 9th, 2009
| Quote
perfect example…
thanks
#10 by Prashant on January 2nd, 2010
| Quote
Thanks for these great tutorials. I am a regular reader of you site from now on. I am now working on a project with CI. Inspired by your tutorial I am going to use doctrine.
#11 by turbod on January 11th, 2010
| Quote
I have a question. This may be the same name both of the controller and the model class name?
#12 by Burak on January 11th, 2010
| Quote
Model and Controller classes can not be the same names.
#13 by Yogesh on January 21st, 2010
| Quote
Hi,
First of all thank you for such a nice tutorial. I liked it very much and very easy to understand.
But I have some issue i was trying ur code on local pc it is working fine but if i put the code on my website it doesn’t work
1. the .htaccess file which u had if i use it then in the login it gives error so i have to put the index.php in the $config['index_page'] = “index.php”; to work
it opens the page to login but the next step when i try to submit using the username and password it gives error as
Fatal error: Uncaught exception ‘Doctrine_Connection_Exception’ with message ‘Couldn’t locate driver named mysql’ in /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Connection.php:492 Stack trace: #0 /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Connection/Mysql.php(101): Doctrine_Connection->connect() #1 /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Connection.php(1008): Doctrine_Connection_Mysql->connect() #2 /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Query/Abstract.php(1094): Doctrine_Connection->execute(’SELECT u.id AS …’, Array) #3 /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Query/Abstract.php(1142): Doctrine_Query_Abstract->_execute(Array) #4 /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Query.php(276): Doctrine_Query_Abstract->execute(Array, NULL) #5 /hermes/web0 in /hermes/web06/b2031/moo.jagson3108/auc/system/application/plugins/doctrine/lib/Doctrine/Connection.php on line 492
#14 by Burak on January 21st, 2010
| Quote
You need to enable the PDO mysql drivers. Should be in your php.ini file.
#15 by Yogesh on January 21st, 2010
| Quote
on the web how can i find the php.ini file?
I m new to php so plz guide me.
#16 by Yogesh on January 21st, 2010
| Quote
Type your comment here
#17 by Burak on January 21st, 2010
| Quote
Did you restart Apache?
#18 by Larry on January 29th, 2010
| Quote
Hi, thanks to your brilliant tutorial, I built up the integration of Codeigniter and Doctrine.
I finished by this “Basic” page and try to call
Doctrine::getTable(’Entries’)->find(2); to retrieve an entry from my DB table.
But got error “Fatal error: Class ‘Doctrine’ not found”.
Is there anything more that I should config?
Thanks & Regards.
Larry.
#19 by Gonzalo on March 16th, 2010
| Quote
Hi, Great Tutorial. I´m having trouble with Doctrine (I guess) it isn´t show me any errors, it´s just show me a blank page.
What could it be wrong?
Thank you.
(Sorry for my english, it´s not my first language)
#20 by michael poplin on March 18th, 2010
| Quote
Thank you for this. You are my hero.
#21 by Valery on April 5th, 2010
| Quote
Very nice tutorial. Thank You.
#22 by Abid on June 14th, 2010
| Quote
Very nicely presented. Can you please tell me about how to integrate doctrine 2.0 in codeigniter. ?? your tutorial is for doctrine 1.2
#23 by Musaddiq on June 30th, 2010
| Quote
thanks doctrine team