I have worked with Ruby on Rails and I was looking for some code that did something close to the wonderfull RoR’s ActiveRecord.

I stepped by this site. Its PHP-ActiveRecord!

I found it amazing, and it was exactly what I was looking for, but I didn’t find anyone trying to use it on WordPress, so I got a little scared.

Any experiences you could share?

My first idea was to require the library in functions.php and create a child theme with the models inside a folder. What I really don’t know is how it’s going to deal with the tables in the database it can’t mess with.

Well, I’ll wait your impressions.

2 Answers
2

If you plan to use it just for your own code, and have it running alongside WordPress’ default database driver (wpdb), I see no real problems.

It’s only if you plan on fully integrating/overriding WP’s driver that I see it being near-impossible; hard-coded SQL is prolific throughout core, and translating them to ActiveRecord method calls would defeat any efforts for code optimisation.

FWIW, WordPress does support a driver override with db.php in your wp-content directory.

Update: For bringing PHP ActiveRecord into WordPress, I would suggest using a MU plugin. This keeps it out of the theme (where it doesn’t belong), out of WordPress core, and ensures that it is always loaded (Must Use plugins cannot be deactivated in the admin).

Copy the library to wp-content/mu-plugins/php-activerecord. Then in wp-content/mu-plugins/php-activerecord.php:

<?php

/**
 * Plugin Name: PHP ActiveRecord
 * Description: Load the PHP ActiveRecord library for use in plugins &amp; themes.
 * Version:     0.1
 * Author:      TheDeadMedic
 * Author URI:  http://wordpress.stackexchange.com/users/1685/thedeadmedic
 * Plugin URI:  http://wordpress.stackexchange.com/a/155530
 */

require_once dirname( __file__ ) . '/php-activerecord/ActiveRecord.php';

ActiveRecord\Config::initialize(
    function ( $cfg ) {
        $cfg->set_model_directory( '/path/to/your/model_directory' );
        $cfg->set_connections(
            array(
                'wordpress' => sprintf( 'mysql://%s:%s@%s/%s?charset=%s', DB_USER, DB_PASSWORD, DB_HOST, DB_NAME, DB_CHARSET ),
            )
        );

        $cfg->set_default_connection( 'wordpress' );
    }
);

Leave a Reply

Your email address will not be published. Required fields are marked *