Friday, July 30, 2010

Codeigniter and Doctrine - ตอนที่ 1 – Install and Setup

CodeIgniter allows us to add plug-ins. That’s how we will be installing it.

1. Create folder: system/application/plugins
2. Create folder: system/application/plugins/doctrine
3. Download Doctrine
           Download Doctrine
4. Extract the files. and copy “lib” folder  to system/application/plugins/doctrine.
    Now your folders should look like this:


    5. Create the plug-in file: system/application/plugins/doctrine_pi.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'];


    // CodeIgniter's Model class needs to be loaded
    require_once BASEPATH.'/libraries/Model.php';

    // telling Doctrine where our models are located


    // this will allow us to use "mutators"
        Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);

    // this sets all table columns to notnull and unsigned (for ints) by default
        array('notnull' => true, 'unsigned' => true));

    // set the default primary key to be named 'id', integer, 4 bytes
        array('name' => 'id', 'type' => 'integer', 'length' => 4));

    Database Setup and Configuration

    • 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

    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.


    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.
    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` (
    `username` VARCHAR( 255 ) NOT NULL ,
    `password` VARCHAR( 255 ) NOT NULL ,
    `first_name` VARCHAR( 255 ) NOT NULL ,
    `last_name` VARCHAR( 255 ) NOT NULL ,
    UNIQUE (

     Create the Model

     Create file: system/application/models/user.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);


    • 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

    // 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';

            $u2 = new User;
            $u2->username = 'phprocks';
            $u2->password = 'mypass';
            $u2->first_name = 'Codeigniter';
            $u2->last_name = 'Doctrine';

            echo "added 2 users";


    We just generated 2 objects, and populated them with some data. Simply calling save() should save them into our database.
    • 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 

    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!

    ที่มา CodeIgniter and Doctrine from scratch Day 1 – Install and Setup



    1 comment: