PHP Programming > Code Snippets
Lazy Object
(1/1)
tomelders:
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...
--- Code: ---$my_user = new LazyObject("SELECT * FROM my_user_table WHERE ID=$id");
--- End code ---
obviously the SQL depends on your table set up, but all your field values are now available like this
--- Code: ---echo("<p>" . $my_object->user_login);
echo("<p>" . $my_object->user_email);
// etc etc
--- End code ---
You can also set your object properties like this...
--- Code: ---$my_object->user_login = "Spartacus";
--- End code ---
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,
--- Code: ---while($my_object->next()):
echo("<p>" . $my_object->user_login);
endwhile;
--- End code ---
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
Zyppora:
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
tomelders:
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
Zyppora:
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
Navigation
[0] Message Index
Go to full version