Messy code .. Can somone help cut it down to minimal code?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

bob_the _builder wrote:To strip the slashes that were added during the ValidateOutput?
Neither ValidateInput nor ValidateOutput add slashes that must be removed.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

With code like in the original post, you might want to instead ask how you could go about writing code that does the same thing -- but in a clean way. I think refactoring is a little too much to ask and you would learn less. With guys like volka and timvw giving you input you could learn a lot.
(#10850)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

In a book i read the following practical tip: Use arrays to store values that have been prepared for use in a given context...

eg:

Code: Select all

$mysql = new array();
$html = new array();


$mysql['content'] = mysql_real_escape_string($_REQUEST['content']);
$html['body'] = htmlentities($row['body'], ENT_QUOTES, 'UTF-8');
Perhaps you could wrap this in a function as following: (untested.. I only want to give an idea of the concept here)

Code: Select all

public abstract class Preparator {
 private  $values;

 public function Preparator() {
  this->values = new array();
 }

 public function Set($key, $value) {
  $this->values[$key] = this->Prepare($value);
 }

 public function Get($key) {
  if (array_key_exists($key, $this->values)) {
   return $this->values[$key];
  } else {
   throw new Exception("There was no value available for the key " . $key);
  }
 }

 public abstract funcion Prepare($value);
}

public class MySqlPreparator extends Preparator {
 public MySqlPreparator() {
  parent::__constructor();
 }

 public Prepare($value) {
  return mysql_real_escape_string($value);
 }
}

public class HtmlPreparator extends Preparator {
 public HtmlPreparator() {
  parent::__constructr();
 }

 public function Prepare($value) {
  return htmlentities($value, ENT_QUOTES, 'UTF-8');
 }
}
Post Reply