Monday, October 21, 2013

Using PHP Generic Objects To Organize Your Code

I like using PHP classes to keep my code organized and easy to maintain. I know that they consume more memory than simply using an array or variable system, but if memory is an issue, I'd get more memory. Saving time by coding in a maintainable fashion is more important to me than upgrading a server. I've written a very generic, flexible PHP class that I use in my PHP code to get and set variables for use within the page.

The PHP Class

/* generic class */
class generic {

 var $vars;

 //constructor
 function generic() {  }

 // gets a value
 function get($var) {
  return $this->vars[$var];
 }

 // sets a key => value
 function set($key,$value) {
  $this->vars[$key] = $value;
 }

 // loads a key => value array into the class
 function load($array) {
  if(is_array($array)) {
   foreach($array as $key=>$value) {
    $this->vars[$key] = $value;
   }
  }
 }

 // empties a specified setting or all of them
 function unload($vars = '') {
  if($vars) {
   if(is_array($vars)) {
    foreach($vars as $var) {
     unset($this->vars[$var]);
    }
   }
   else {
    unset($this->vars[$vars]);
   }
  }
  else {
   $this->vars = array();
  }
 }

 /* return the object as an array */
 function get_all() {
  return $this->vars;
 }

}

Simple Usage

/* simple usage -- just gets and sets */
$person = new generic();

// set sample variables
$person->set('name','David');
$person->set('age','24');
$person->set('occupation','Programmer');

// echo sample variables
echo '<strong>Name:</strong> ',$person->get('name'),''; // returns Name: David
echo '<strong>Age:</strong> ',$person->get('age'),''; // returns Age: 24
echo '<strong>Job:</strong> ',$person->get('occupation'),''; // returns Job: Programmer

// erase some variables -- first a single variable, then an array of variables
$person->unload('name');
$person->unload(array('age','occupation'));

Database Usage

/* database-related usage */
$query = 'SELECT name,age,occupation FROM users WHERE user_id = 1';
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);

$user = new generic();

$user->load($row);
// echo sample variables
echo '</strong>Name:</strong> ',$user->get('name'),''; // returns Name: David
echo '</strong>Age:</strong> ',$user->get('age'),''; // returns Age: 24
echo '</strong>Job:</strong> ',$user->get('occupation'),''; // returns Job: Programmer

Save To The Session, Retrieve From The Session

$_SESSION['person'] = $person->get_all();

/* and on the next page, you'll retrieve it */

$person = new generic();
$person->load($_SESSION['person']);
Let me know your thoughts on this type of class. Do you have any suggestions for improvement?