Lazy Object


#1

This may be useful for anyone working with MySQL tables (which I imagine includes everyone) who would like to take an object orientated approach to the development.

http://www.tomelders.com/resource/LazyObject.php.zip

This object will take a mysql select query and create an object out of it. so say you have a user table…

$my_user = new LazyObject("SELECT * FROM my_user_table WHERE ID=$id");

obviously the SQL depends on your table set up, but all your field values are now available like this

echo("<p>" . $my_object->user_login);
echo("<p>" . $my_object->user_email);
// etc etc

You can also set your object properties like this…

$my_object->user_login = "Spartacus";

Lazy Object will take care of updating your MySQL table for you automagically.

also, if you don’t include a WHERE clause in your query, or your query returns more than one row you can use the next() method,

while($my_object->next()):
   echo("<p>" . $my_object->user_login);
endwhile;

There are also a bunch of other methods in there but right now I need to clean it up a little. I also doubt that I’m the first person to do this and I doubt it’s the smoothest execution possible, but I’m finding it useful, I hope someone here does too. It’s open source and all that so feel to share and make better.

Peace Out
-t


#2

Just my .02c:

You seem to attempt to stop any changes to a primary key by filtering out ‘ID’ in various ways from the attribute in your sql_assign() method. I’d suggest looking up any primary/unique/foreign/etc. keys and mapping them using the following two functions:

http://nl2.php.net/manual/en/function.m … d-name.php
http://nl2.php.net/manual/en/function.m … -flags.php

I’m too lazy right now to actually cough up a decent replacement script though :P


#3

thanks for the pointer, I knew there must have been a better way of doing that. I’ll update it over the weekend hopefully and post again on monday.

-t


#4

Oohw, big bug there. Where do you initiate the MySQL connection in the class? You can’t expect the MySQL handle to be a (super)global variable, and since your construct starts out with the read() function, which runs a query, it should fail :)