Chief Technology Officer & Photographer | Irvine, CA

Codeigniter & PHP ActiveRecord

I recently started using PHP ActiveRecord with a CodeIgniter project at work, and I’m absolutely in love with it, especially since it now makes CodeIgniter work just like Ruby on Rails when dealing with models.

I had previously started writing my own ORM style model that plugged in to CodeIgniter, but after finding PHP ActiveRecord and then finding a Spark wrapper for PHP ActiveRecord to integrate in to CodeIgniter, I have since abandoned the “base_model” project, and I’ll show you how to integrate these 2 in this post.

To integrate PHP ActiveRecord in to your existing CodeIgniter project, follow these steps (from the root of your project & I’m assuming you already have your database settings set inside application/config/database.php, but TURN OFF AUTOLOADING of the Database class if you have it set – it will cause this to throw errors):

1. Install the Sparks Manager (if you haven’t installed it already)

php -r "$(curl -fsSL http://getsparks.org/go-sparks)"

2. Install the PHP ActiveRecord Spark

php tools/spark install -v0.0.1 php-activerecord

3. Activate PHP ActiveRecord in your controller. (I generally have a “MY_Controller” controller setup in between all my controllers and the CI_Controller to create an “Application Controller” of sorts. If you are a Rails developer, you know what I’m talking about. Application controllers give you a global controller to handle things like auth/etc.)

class MY_Controller extends CI_Controller { 
    function __construct() { 
        parent::__construct(); 
        $this->load->spark('php-activerecord/0.0.1'); 
    } 
}

4. Create a table called “Users” with a few fields

DROP TABLE IF EXISTS users;
CREATE TABLE users ( 
    id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    email_address VARCHAR(200) NOT NULL DEFAULT '' 
) ENGINE=InnoDB;

5. Create your “User” model in application/models/User.php

 class User extends ActiveRecord\Model {} 

6. Test in one of your controller functions (possibly welcome/index)

$user = new User(array("email_address" => "beau.frusetta@gmail.com")); 
$user->save(); 

## This should show you the User record that you just created 
print_r($user); 

## Now do a simple find by email address 
$user = User::find_by_email_address("beau.frusetta@gmail.com"); 
print_r($user); 

## Now do a simple find by primary key 
$user = User::find(1); 
print_r($user); 

And that’s basically it. There is tons of functionality built in to PHP ActiveRecord – check out the documentation to find everything you might need, and if you have any questions, let me know with a comment below.

Comments

  1. sherwin says:

    looks like you’re doing the query in the controller, not the model. are you no longer using the model? i’ve been trying to see examples of how the model is implemented. from the activerecord site, they aren’t using methods in the model class. if you are using the model class with, could you share a controller and model example? thanks.

    • For this “example”, I was just showing how to setup the model and access the data quickly.

      If you have a need to access information over the basic queries that PHP ActiveRecord gives you, I’d say build out functions in your model to handle that.

      To do that, you’d just create a standard public function, and then reference the model using self::find() or something to that effect.

      I’m a firm believer in Skinny Controllers/Fat Models, so all of your processing/logic should go in to your models when necessary and your controllers should only act as routers of requests and information to the views.

      Does that make sense?

      • sherwin says:

        thanks, it does make sense except the self::find(). just need a little more info. currently i do have fatter models and skinny controllers. so if i had a function called authenticate() in my model, i would call it in my controller as self::authenticate()? usually it’s $this->users_model->authenticate(). and in the controller, do i put that inside a if ($this->input->post()) conditional statement? right now CI is handling my validation so my model is inside the validation->run().

        • It depends on how you’ve declared the function inside your model. If you’ve declared the function as static, as in “public static function authenticate()”, then you’d call it, from within your model functions, as self::authenticate(). If you’ve just declared it as a standard public function, “public function authenticate()”, you’d call it like self->authenticate(). Static functions can be called on an object, the model, without an object instantiated – you just have to make sure you don’t reference any variables or functions that require an instantiated object.

          For an authentication function, let’s say it’s attached to a User model (I’d assume). You could setup your function as a static function – public static function authenticate(). Then, in the controller that processes the post from your form, you could call “if (!empty($_POST))” and then include the static call to authenticate – “User::authenticate()” – inside that if/then block.

          When your model executes the authenticate() function, you will have access to your post variables, just make sure to use codeigniter’s input class by declaring a variable that references the CI instance at the beginning of the authenticate() function – “$CI =& get_instance();” – then referencing “$CI->input->post()” to grab your posted variables.

Trackbacks

  1. […] here: Codeigniter & PHP ActiveRecord Bookmark to: This entry was posted in Uncategorized and tagged active, especially-since, […]

  2. […] the original post: Codeigniter & PHP ActiveRecord RSS feed for comments on this post | TrackBack URL | Leave a […]

Speak Your Mind

*