Well, I know I haven’t created anything new here – but as Frank said, “I did it my way!”
I recently found myself creating more and more objects to store data within apps. I’m not going to get into all the ins and outs of why this is good practice, but it lead me to whipping up this simple script. I had seen a few other similar tools on the inter-webs but none of them worked quite like I needed.
If you’e not familiar with the OO approach for storing data within a script (is there a better way to describe this?) here the gist.
Say you are storing user profile information in your favorite RDBMS. You have a user profile page and will pull data for a specific profile to use in that page. Well, instead of just doing a fetch and grabbing data – creating a bunch of variables, etc., you can take the OO approach. Load all those vars into an object, with nice features like getters and setters – which may manipulate the data, etc. Then you have a clean interface to the data.
My IDE doesn’t have any wizards for this stuff (I think Eclipse can – or has plugins that can) and it can be a bit time consuming to do. Also – its very repetitive to get your basic class structure together. SO – why not write a little script to do this! Like I said, I have seen some others out there that were apparently written for PHP4 or just didn’t format the methods like I prefer.
Check it out and let me know what you think.
http://webguru.org/getset
The resulting class allows you to do stuff like this:
<?php
// create an array of basic user data
$data = array();
$data["user_id"] = 3;
$data["name"] = "Brian Bell";
$data["email"] = "brian@example.com";
$user = new UserDataObj( $data );
echo "User {$user->get_name()} has an id of {$user->get_id()} and an email address of {$user->get_email()}. ";
/*
You can also instantiate the object with no argument,
and set things manually
*/
$user = new UserDataObj();
$user->set_name("Brian Bell");
$user->set_email("brian@example.com");
// also comes in handy to pass the data object to your CrUD methods
$new = new Users();
/*
pass in the data object from above so
the create_user() method has everything it needs.
*/
$new->create_user( $user );
?>
Let me know if you have any comments or suggestions. I don’t have a lot of time to contribute to it – but I can easily see how it could be extended to give the user some options on formatting, etc.
There is a great property generator you can try out here:
http://tools.morkalork.com/php/propertyGenerator/