Recently I’ve been learning Ruby, and at the same time Rails, with it I’ve learnt alot of good standardised ways of things to do, but without a doubt the most powerful part of Rails, for me, was ActiveRecord. So I had a search around the net and came across this fantastic little ActiveRecord implementation in PHP, called php.activerecord. In fact its so amazing I thought I would write a little guide for you to get up and running quickly with it.
We are going to create a quick and dirty model that will represent a blog post.
Please note: the version of Zend Framework when this article was written was 1.10.6
Download php.activerecord from http://www.phpactiverecord.org (version as of writing this is 1.0)
Extract the file, and place it somewhere on your webserver (I put mine in my “library” directory, along with Zend Framework)
Open your Bootstrap.php file for your application, add a protected function for initialising php.activerecord:
protected function _initActiveRecord() {
include_once('/path/to/php-activerecord/ActiveRecord.php');
ActiveRecord\\Config::initialize(function($cfg) {
$cfg->set_model_directory(APPLICATION_PATH.'/models');
$cfg->set_connections(array(
'development' => 'mysql://username:password@host/development_db_name',
'production' => 'mysql://username:password@host/production_db_name',
));
$cfg->set_default_connection(APPLICATION_ENV);
});
}
Set up a database table called ‘posts’ (notice the plural, this is because it holds multiple “Post” models).
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`excerpt` text COLLATE utf8_unicode_ci,
`content` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;
Now create your model, under the “models” directory which we created during the initialisation of php.activerecord that will look something like this (notice Post is singular, this is because your model represents a singular version of what it represents)
<?php
class Post extends ActiveRecord\\Model {
}
?>
Now you have a guide how to get up and running, take a look at the various guides available on the php.activerecord wiki to see how you would use it within your controllers.
If you find this useful, then please leave a comment and let me know. If lots of people enjoy it then I’ll create a step by step tutorial on how to get something up and running using it. Also if you have any questions then leave a comment and I’ll do my best to help wherever I can.
Published on Monday, 12 July 2010