Page 1 of 1

Input(Request) Gathering Class

Posted: Wed Jan 16, 2008 9:10 am
by Zoxive
PHP5 only class. Not sure if it will help others, but it saves me a great deal of time instead of checking each time to see if the variable is set. If its not it returns null(False on complete fail).

There is a little filtering done at the end, but nothing major.

There is no Constructor, because I pass this around in my Register Class, to each Controller/Module in my custom MVC.

Code: Select all

/**
 *  Input - Class for Getting Data From Super Globals
 * 
*/ 
 
class Zox_Input{
  
  /**
   *  Allowed Calls From the Global Arrays
   *  
   *  @access protected
   *  @var array
  */
  protected $Calls = array(
    '_POST', '_GET', '_REQUEST', '_SESSION', '_COOKIE'
  );
 
  /**
   *  Magic Call Function - Magic Happens Here
   *  
   *  @param string $Func
   *  @param array $Args
   *  @return mixed
  */
  public function __call($Func, $Args=array()){
    $Func = '_' . strtoupper($Func);
    if(!in_array($Func,$this->Calls)) return false;
    $Num = count($Args);
    // Return Whole Data For Just one
    if($Num===0) return $this->returnType($GLOBALS[$Func]);
    return $this->multiArg($Args,$Func);
  }
  
  /**
   *  MultiArguments
   *  
   *  @param array $Args
   *  @param string $Func 
   *  @return mixed
  */
  protected function multiArg(array $Args,$Func){
    $Tmp = array();
    foreach($Args as $Num=>$Val){
      if(is_array($Val)) // Input is Array Walk Input (For Grabing Mutidem Array)
        $Tmp = array_merge($Tmp,$this->WalkInput($Val,$Func));
      else
        $Tmp[$Val] = $this->returnType($GLOBALS[$Func][$Args[$Num]]);  
    }
    $Tmp = (count($Tmp)<=1)? current($Tmp) : $Tmp;
    if(empty($Tmp)) $Tmp = NULL;
    return $Tmp;
  }
 
  /**
   *  WalkInput - Recursive Function
   *  
   *  @param array $Arr
   *  @param $Func
   *  @param array $Chng, How Deep we are in the GLOBALS array
   *  @return array
  */
  protected function WalkInput(array $Arr,$Func,$Chng = array()){
    $Tmp = array();
    $Ref =& $GLOBALS[$Func];
    foreach($Chng as $N){
      if(!empty($Ref[$N]) && is_array($Ref[$N])){
        $Ref =& $Ref[$N];
      }
    }
    foreach($Arr as $Key=>$Name){
      if(is_array($Name)){
        $Ch   = array_merge($Chng,array($Key));
        $Tmp  = array_merge($Tmp,$this->WalkInput($Name,$Func,$Ch));
      }else{
        if(is_int($Key)){
          $Tmp[$Name] = $this->returnType($Ref[$Name]);
        }else{
          if(!empty($Ref[$Key][$Name])){
            $Tmp[$Name] = $this->returnType($Ref[$Key][$Name]);
          }
        }
      }
    }
    return $Tmp;
  }
 
  /**
   *  Type of Value
   *  
   *  @param mixed $Var
   *  @return mixed
  */
  protected function returnType(&$Var){
    switch(true){
      case is_int($Var):
        return (int) $Var;
        break;
      case is_array($Var):
        return $this->WalkData($Var);
      case strtolower($Var)=='true':
        return true;
        break;
      case strtolower($Var)=='false':
        return false;
        break;
      default:
        return $this->cleanup($Var);
    }
  }
 
  /**
   *  Loop threw the Array
   *  
   *  @param array $Arr
   *  @return array
  */
  protected function WalkData(array $Arr){
    $Build = array();   
    foreach($Arr as $id=>$Val){
      $Build[$id] = $this->returnType($Val);
    }
    return $Build;
  }
 
  /**
   *  Basic Cleanup More on this later
   *  
   *  @param string $Var
   *  @return mixed
  */
  protected function cleanup($Var){
    // Replace All Line Breaks Make them \n
    $Var = preg_replace("/\015\012|\015|\012/","\n",$Var);
    // All Tabs with a Space
    $Var = str_replace("\t",' ',$Var);
    $Var = trim($Var);
    if(empty($Var)) return NULL;
    return $Var;
  }
}
$_GET Examples:

Code: Select all

$Input = new Zox_Input();
// Url = index.php?Page=home
$Page = $Input->get('Page');
 
// Url = index.php?Page=home&Section=2
list($Page,$Section) = $Input->get(array('Page','Section));
 
 
 
$_SESSION Examples:

Code: Select all

$Username = $Input->session(array('User'=>'Username'));
// Same as $_SESSION['User']['Username'];
 
list($ID,$Username) = $Input->session(array('User'=>array('Admin'=>array('ID','Username'))));
// Same as array($_SESSION['User']['Admin']['ID'],$_SESSION['User']['Admin']['Username']);
 
I wrote this about a 2 weeks ago, and haven't fully tuned it for speed yet, any comments, concerns, critique appreciated.

Re: Input(Request) Gathering Class

Posted: Wed Jan 16, 2008 4:32 pm
by Benjamin
For something that simple I don't see a need to make it oo.

Code: Select all

 
function get($i)
{
    return (isset($_GET[$i])) ? $_GET[$i] : null;
}
 
function post($i)
{
    return (isset($_POST[$i])) ? trim($_POST[$i]) : null;
}
 
function cookie($i)
{
    return (isset($_COOKIE[$i])) ? $_GET[$i] : null;
}
 
function session($i)
{
    return (isset($_SESSION[$i])) ? trim($_SESSION[$i]) : null;
}
 
Usage:

Code: Select all

 
$page = get('page');
 

Re: Input(Request) Gathering Class

Posted: Wed Jan 16, 2008 7:58 pm
by Zoxive
Its a class because, I only use it inside of my Controllers, and Modules. Which my MVC autoloads this class from the Registry which is passed to the Controller/Module. So I never have to declare the object, its always there.

It saves me plenty of lines, and makes me happy.

Code: Select all

 // Inside Controller
// ...
public function registerAction(){
    $this->loadModule('user_register','Register');
    $Created = false; // Default False
    $PostData = $this->input->post(
      'Username', 'Password1',  'Password2',  'Name', 'Email',
      'Country',  'Zip',        'Month',      'Day',  'Year',
      'Agree',    'Gender'
    );
    if(!empty_array($PostData)){
      try{
        $Created = $this->Register->CreateUser($PostData);
      }catch(Exception $e) {
        // Catch Exception from MySql or Failed Validation
      }
    }
    if($Created){
      $this->Register->SendActivationMail();
      $this->queViewAs('user_success',$this->Main);
    }else{
      $this->queViewAs('user_register',$this->Main);
    }
  }
The only problem I have with this class, is I currently can not Set Variables. Like for instance, $_SESSION Data. I still have to do it like normal. Ex. $_SESSION['User']['id'] = $UserID;
I haven't thought of a good way to do that yet.

Re: Input(Request) Gathering Class

Posted: Thu Jan 17, 2008 1:05 pm
by Benjamin
Why not just call functions from inside your Controllers/Modules and avoid having it autoloaded from the registry and passing it to the Controller/Module. It's only purpose is to avoid using isset all the time correct?

Re: Input(Request) Gathering Class

Posted: Thu Jan 17, 2008 1:41 pm
by Zoxive
astions wrote:Why not just call functions from inside your Controllers/Modules and avoid having it autoloaded from the registry and passing it to the Controller/Module.
I guess that does make a lot of sense, less overhead. :banghead:
astions wrote:It's only purpose is to avoid using isset all the time correct?
Essentially yes, I can also group them so it returns an array, then I can easily pass that array to my other modules, etc. And then I know that it is set (NULL for empty). It saves me checking isset/!empty multiple times.

Like in my last post, the controller example.

Code: Select all

$PostData = $this->input->post(
      'Username', 'Password1',  'Password2',  'Name', 'Email',
      'Country',  'Zip',        'Month',      'Day',  'Year',
      'Agree',    'Gender'
    );
Instead of

Code: Select all

 
$PostData = array(
  'Username' = !empty($_POST['Username'])? $_POST['Username'] : null,
  'Password1' = !empty($_POST['Password1'])? $_POST['Password1'] : null,
  'Password2' = !empty($_POST['Password2'])? $_POST['Password2'] : null,
  // Etc
);