PHP Active Record Class
This page needs an update!
Beware that the code listed here has numerous bugs and is only intended for research purposes. Please contact me if you are interested in a newer, more polished version.
I had seen and heard a lot about Active Record and wanted to have some fun with it. As I'm mostly a PHP guy, I decided to roll out my own class. This is what I came up with. It never really made it to production so it's probably a bit rough, but I've learned a lot about the internals of AR and frankly, had a lot of fun programming this. It has support for renderer class extensions (ie: to generate an xml output), in model validation functions, etc. I've used the occasion to get accustomed with xDebug, the PHP remote debugger. You can view a live example here (reload to see the effect).
Note that this is test code and the errors are expected for debugging. See attached file for the source.
Usage Example
<?php /** * Define a table model **/ class activeRecordTest extends tableAbstract { public $rootXPath = '/appData/pageData'; function __construct(tableRenderer &$renderer = null) { $this->_init(__CLASS__, $renderer); } protected function onCreate() { $tableName = $this->myName; $tableSQL = <<<SQL CREATE TABLE `${tableName}` ( `id` mediumint(8) unsigned NOT NULL auto_increment, `login` varchar(128) character set latin1 NOT NULL, `password` varchar(45) character set latin1 NOT NULL, `email` varchar(255) character set latin1 NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci SQL; return $tableSQL; } public function loginExists($login) { if ($this->fetchRow(HP('limit', 1)) > 0) return true; else return false; } /** * Custom, auto-called, field validation function **/ protected function validate_login($data) { if (rand(0, 1) == 0) return true; else return false; } } // END table model Pages $myTest = new activeRecordTest(new xmlRenderer); $myTest->login = 'User'; $myTest->password = 'password'; // Use of a custom model method echo 'User jdoe <b>' . (($iExists = $myTest->loginExists('jdoe')) ? 'exists' : 'doesn\'t exist') . "</b>\n"; if ($myTest->fetchAll() == 0 || !$iExists) { $myTest->email = 'jdoe@example.org'; $myTest->password = sha1('jdoe'); $myTest->login = 'jdoe'; if ($myTest->saveData()) { echo '<b>Saved data 1</b>' . "\n"; } else { echo '<b style="color red">Failed to save 1</b>' . "\n"; } } $myTest->fetchRows(HP('fieldName', '*')); ?> <pre> <h2>tableRenderer generated XML</h2><hr /> <?php echo htmlentities($myTest->render(true)); ?> </pre>
Attachments
-
ar.php.txt
(46.8 KB) - added by mlalonde
4 years ago.
Active Record Class in PHP5