473,386 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

PHP OOP Setters and Getters + data validation

3
Hi,
I was reading topic about setters and getters (http://www.thescripts.com/forum/thread631267.html) and wanted to ask, how they should be used? I have noticed that a general data validators suck, since the amount of different possibilities how to validate data is endless (like Jerry S said well in the topic, after some time the general data validator gets longer and longer. slower and slower + harder to maintain and more subject to errors.) so i thought, it's more sensible to create datavalidator within one class. but when i was horny all over my code, i bumbed into few problems:

1) should i validate the data both when setting and getting it?
2) when i set the data, should i validate it for database or for object (should i use mysql_real_escape_string when setting the data)?
3) should i set properties always by using set-methods (also e.g. in page constructor)?
4) if i don't use set-methods for properties within class, should the data be validated when setting properties? or should i use set-methods before saving the data to database (in save() method)?
5) should the data be validated in db class?
6) summary: i know i HAVE TO use mysql_real_espcape_string (plus strip_tags function) when i put data into database and stripslashes (plus some str_replace functions) when getting it out from database, but at which point? should i do all datacleaning and validation in page class? should get-methods be used when loading data from database within class with stripslashes etc validation?

I have 2 classes, db-class for database connections etc and page-class for creating pages (don't worry about the lack of errorhandling, i excluded it from this example).


[PHP]
define("DB_HOST", "myhost");
define("DB_USER", "myuser");
define("DB_PASS", "mypass");
define("DB_NAME", "mydb");


// ===============
// CLASS DB
// ===============
class db {
private $connection;
private $sql;
private $lastId;
private static $instance;

private function __construct() {
$this->connect();
}

// singleton method
public static function create() {
if (!isset(self::$instance))
self::$instance = new db();
return self::$instance;
}

public function connect($dbHost=DB_HOST,$dbUser=DB_USER,$dbPass=DB _PASS,$dbName=DB_NAME) {
$this->connection=mysql_connect($dbHost,$dbUser,$dbPass) ;
mysql_select_db($dbName,$this->connection);
}

// for SELECT statements
public function fetch($sql=""){
$result = mysql_query($this->sql,$this->connection);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$data[] = $row;
mysql_free_result($result);
return $data;
}

// for INSERT, UPDATE and DELETE statements
public function execute($sql="") {
mysql_query($sql,$this->connection);
// set lastId property
$lastId = mysql_insert_id();
$this->setLastId($lastId);
}

public function setLastId($lastId) {
$this->lastId = $lastId;
}

public function getLastId() {
return $this->lastId;
}
}

// ===============
// CLASS PAGE
// ===============
class page {
private $id;
private $title;
private $text;

public function __create($id=NULL,$title,$text) {
if ($this->validateId($id)>0) {
$this->id=$id;
$this->title=$title;
$this->text=text;
}
}

public function setId($id) {
$id = $this->escape($id);
$id = $this->validateId($id);
$this->id = $id;
}

public function setTitle($title) {
$title = $this->escape($title);
$title = $this->stripTags($title);
$this->title = $title;
}

public function setText($text) {
$text = $this->escape($text);
$text = $this->stripTags($text);
$this->text = $text;
}

public function getId() {
return $this->id;
}

public function getTitle() {
return $this->title;
}

public function getText() {
return $this->text;
}

public function save($id=NULL) {

$this->setId($id);
$db = db::create();

if ( ($id === NULL) || ($id === 0) ) {
$sql="INSERT INTO page (title,text) VALUES ('$this->title', '$this->text'");
$result = $db->execute($sql);
// set new id for current pageobject
$this->setId($db->getLastId());
}
else {
$sql = "UPDATE page SET title='$this->title', text='$this->text' WHERE id = $this->id";
$db->execute($sql);
}
}

public function load($id=NULL) {

$this->setId($id);
$db = db::create();

$sql = "SELECT * FROM page WHERE id = " .$this->id;
$data= $db->fetch($sql);

if ($data) {
$sizeOfData = sizeof($data);
for ($i=0; $i<$sizeOfData; $i++) {
$this->setId($this->cleanData($data[$i]['id']));
$this->setTitle($this->cleanData($data[$i]['title']));
$this->setText($this->cleanData($data[$i]['text']));
}
}
}

// PAGE CLASS VALIDATORS
private function validateId($id) {
if (!empty($id) && is_numeric($id) && ($id > 0))
return (int) $id;
else
return 0;
}

private function stripTags($input, $allowedTags = "<p><a><img><b><u><i><li><ul><table><td><tr><b r>") {
return strip_tags($input, $allowedTags);
}

// if magic quotes are ON, remove the slashes that it added,
// and add slashes with mysql_real_escape_string-function.
// this is because magic quotes or addslashes-function do not escape
// values \x00, \n, \r, and \x1a (which may be used in SQL injection)
private function escape($input) {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
$input = mysql_real_escape_string($input);
}
else $input = mysql_real_escape_string($input);
return $input;
}

private function cleanData($txt="") {
$txt = stripslashes($txt);
$txt = str_replace('"','\'', $txt);
$txt = str_replace('<br />', '', $txt);
return $txt;
}
}

$page = new page();
$page->setTitle("Foo");
$page->setText("Bar");
$page->save();
$page->load(1);
echo $page->getTitle()."<br>";
echo $page->getText();
[/PHP]
Mar 30 '08 #1
3 6566
ronverdonk
4,258 Expert 4TB
You don't really expect our members to read through that bunch of unstructured code, do you?

First read the Posting Guidelines about enclosing code within the appropriate code tags, then apply the tags to your post and then we will have a look.

moderator
Mar 30 '08 #2
planey
3
You don't really expect our members to read through that bunch of unstructured code, do you?

First read the Posting Guidelines about enclosing code within the appropriate code tags, then apply the tags to your post and then we will have a look.

moderator
hehehe, thats what i was doing when i was reading the old post!
but thanks, changed now, looks much better nowadays!
Mar 30 '08 #3
planey
3
Since no1 seems to reply, i guess i'll just do the following:

1) Set each property ALWAYS with their own setmethods (not $this->property = 'foo'). In the set-method, i'll add slashes to property with mysql_real_escape_string-function and validate the data with strip_tags-function

2) Get each property outside the class with get-methods (of course, they are set to private, so $page->property will result in error), clean the data in get methods with stripslashes function, and do some str_replacing. So get-methods are used for printing the data in webpage

3) In the class, use $this->property (not get-method) e.g. when referring to property which is being inserted/updated into database (and has been set with set-method).

Sounds sensible, no?
Or is there better ways to use setters & getters?
Apr 1 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

27
by: Stuart Gerchick | last post by:
C++ Coding Standards : 101 Rules, Guidelines, and Best Practices by Herb Sutter, Andrei Alexandrescu is now a month or so away from release. What is people's opinion on this...is it going to be a...
32
by: kelvSYC | last post by:
I'm familiar with get and set function paradigms from Java, but what's the recommended design for such in C++? Should it be like so: foo& getFoo(); void setFoo(foo& f); or like so: foo&...
2
by: Lachlan Hunt | last post by:
Hi, In JavaScript 1.5, objects can use special getter and setter functions for properties. However, these only seem to be implemented in Gecko and, AFAICT, don't seem to be part of ECMAScript. ...
2
by: Wei Wang | last post by:
Greetings, I find the JavaScript's Object.prototype and getter/setter mechanism very nice. However, I need some help with extending an object with getters/setters in the derived class. For...
13
by: Neil Zanella | last post by:
Hello, It seems to me that C# properties are nothing more than syntactic sugar for getters and setters. I wonder whether others hold a different point of view. Basically, what more do they have...
112
by: mystilleef | last post by:
Hello, What is the Pythonic way of implementing getters and setters. I've heard people say the use of accessors is not Pythonic. But why? And what is the alternative? I refrain from using them...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.