codeigniter_doctrineIn 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!

"CodeIgniter and Doctrine from Scratch" Series: