Monday, May 30, 2011

Issues while integrating PHP ActiveRecord with CodeIgniter 2.0.2

Intro
Being tired of having a trying to fully utilize CodeIgniter's built-in ActiveRecord (which is really  a loose interpretation of the ActiveRecord design pattern if you ask me), I decided to look for a standalone PHP ActiveRecord implementation. I followed Matt Machuga's tutorial for integrating PHP ActiveRecord with CodeIgniter (I had some issues with his newer revised tutorial).

First Issue: PHP ActiveRecord not loading values into class object.
PHP ActiveRecord appeared to be working except that it would not load the class values. The class structure were defined by the database table and were accessible. Creating and saving a model worked.

First Solution: Remove Constructors
PHP ActiveRecord wasn't loading object values from the database. After some searching, I found a forum on phpactiverecord.org specifing that your model classes can't use constructors (without respect to signature in PHP ActiveRecord). After removing the constructors, data would populate perfectly.

Second Issue: Storing in Session (or psudo-session)
So it appears that CodeIgniter uses cookies to store session data, not PHP's native session. Their implementation also did not support namespace classed (like our model that extends ActiveRecord/Model).

Second Solution: Go PHP Native Sessions
I decided to integrate the NativeSession library for CodeIgniter. This library claimed to allow you to use the session the same but it would integrate with PHP's native session. Be sure to follow the instructions and comments carefully for CI 2.0.*. So far it has been working without issues.

Third Issue: __PHP_Incomplete_Class Object
This happens when you are trying to access a class definition without it's presence. In other words, PHP wants to have access the actual class file for the class it is trying to instantiate.

Third Solution: Order of Loading Libraries
In CI libraries are loaded in the order they are specified. In our now reconfigured solution, we are autoloading session and activerecord (and anything else your using). In order for our new PHP Native Session to know which class definition an instance has, it needs access to our ActiveRecord library. This means changing the loading order to first load activerecord and then load session will fix out problem.
$autoload['libraries'] = array('ActiveRecord', 'session');
After all this, everything appears to be working properly. If any issues arise, I'll update my post with solutions I find.

Best of luck.