Text Class

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

Post Reply
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Text Class

Post by Nay »

It's OOP fever for me now. I took a look at PHP5 and have gone w00t. I wish there was private and public methods with PHP4........or is there? ;).

Anyhow. I wrote the following text class out of fustration after validating in every script and everytime I had a new idea I had to change all my files. I am a little too deep into the project to re-do the validation. I'd be great if any of you can improve the class a little :).

Code: Select all

<?php

class text {
   
   var $array = null; // set the array
   var $log = ''; // any errors?
   
   var $required = null; // for validation, say you only want the fields name and password out of 5 or s6 fields
   var $requiredErrors = ''; // more errors? =\
   
   function setArray($array) {
      $this->array = $array;
   }
   
   function getArray() {
      return $this->array;
   }
   
   function unformat() {
      $temp = array(); // make a temp array
      foreach($this->array as $key => $value) {
         $value = strip_tags($value);
         $value = trim($value);
         $value = addslashes($value);
         $temp[$key] = $value; // unformat the value and set the key to the new value
      }
      $args = func_num_args(); // optional functions you wish to call (eg: htmlentities) that were not included originally
      if($args > 0) { // if there's more than 0 optional functions to do
         for($i = 0; $i < $args; $i++) {
            if(function_exists($args[$i])) {
               foreach($temp as $key => $value) {
                  $value = $args[$i]($value); // execute the function with the value as an argument
                  $temp[$key] = $value;
               }
            } else {
               // do nothing, but log it
               $this->log .= "Call to undefined function: " . $args[$i] . " | ";
            }
         }
      }
      $this->array = $temp; // update the array
   }
   
   function format() {
      $temp = array(); // same thing as above, probably the opposite =\
      foreach($this->array as $key => $value) {
         $value = addslashes($value);
         // any other functions?
         $temp[$key] = $value;
      }
      $args = func_num_args(); // optional functions
      if($args > 0) {
         for($i = 0; $i < $args; $i++) {
            if(function_exists($args[$i])) { // if that function exists
            foreach($temp as $key => $value) {
               $value = $args[$i]($value); // execute the function with the argument
            }
            } else {
               // do nothing, but log it
               $this->log .= "Call to undefined function: " . $args[$i] . " | ";
            }
         }
      }
      $this->array = $temp;
   }
   
   function validate() {
      $error = 0;
      $errorKeys = array();
      foreach($this->required as $key => $value) {
         if(empty($this->array[$value]) || !isSet($this->array[$value])) {
            $error += 1;
            $errorKeys[] = $key;
         } else {
            // do nothing
         }
      }
      if($error == 0) {
         return true;
      } else {
         $this->requiredErrors = $errorKeys;
         return false;
      }
   }
   
}

?>
I wouldn't count this as a code snippet.....maybe not yet. I'm positive any of my classes I write can be advised by the lot of you ;).

Er.....not qads, he's outside :lol:

-Nay
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

1. Class names generally start with upper case. In this case 'Text'
2. You normally use a constructor to .. ummm ... construct ...
3. In your validate method, you don't need $error, just use count($errorKeys) to check the number of errors

Oh yea .. what is the point of this class?

Eli
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Re: Text Class

Post by Nay »

Nay wrote:I wrote the following text class out of fustration after validating in every script and everytime I had a new idea I had to change all my files.
Say you want to handle a form to check if any of the required fields were left blank or so. You can do it like:

Code: Select all

<?php

$text = new text();
$text->setArray($_POST);

$text->required = array("username", "password");
$result = $text->validate();

if(!empty($result)) {
echo "Sucess";
} else {
echo "You have missed out some fields";
// you can also print out the missed out fields, which are in the array requiredErrors
}

?>
Hope that made sense 8O

-Nay
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

Ahh ... ok ... got it.

Nice idea. Though for more thorough checking, you would want to check for more then empty. This would be incredible help I think. Checking for regular expressions and object types would be great. I've got bit too much on at the moment to look into that, so if you start implementing it, do post it for the rest of us.

And more importantly - the idea of OOP is to group together objects (and methods on those objects) that belong together to form a logical unit - 'modularity'

You really should have a validation class and another class for the formatting/unformatting. They don't belong together as far as i can see.

Cheers,
Eli
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Post by Nay »

Advice and help always appriciated Yogi ;)...

Ah, logical unit. I need to research on that a little.

Nice pic at your site btw:

Image

We should have a PHP version too, you know, just in case ;)

-Nay
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Re: Text Class

Post by qads »

Nay wrote:Er.....not qads, he's outside :lol:
so you wanna play that way eh? :twisted:

i wrote this in very distressed mind, personally i think its the cigarettes casuseing sleeples nights 8O, i woke up at 10am, 27th, it is now 10am 28th, you do the maths cos i dont know where the hell i am at the moment.

Code: Select all

<?php
//work from last night
class form_validation
{
//
function select_post_fix($values, $lables, $selected)
{
if(empty($_POST[$selected]))
{
$disp = "<option value="" selected><-- Select One --></option>\n";
}
if(!empty($values))
{
$val = explode(",", $values);
$val_ok = 1;
}
$lab = explode(",", $lables);
//
for($x = 0; $x<=count($lab); $x++)
{
$value = $lab[$x];
if($val_ok = 1)
{
$value = $val[$x];
}
if(!empty($lab[$x]))
{
echo "$value == $_POST[$selected]\n";
if($value == $_POST[$selected])
{
$disp .= "<option value="".$value."" selected>".$lab[$x]."</option>\n";
}
else
{
$disp .= "<option value="".$value."">".$lab[$x]."</option>\n";
}
unset($value);
}
}

return $disp;
}
//
function unset_post()
{
for($x = 0; $x<=count($_POST); $x++)
{
unset($_POST[$x]);
}
}
//
function clean_fields($field)
{
$field = addslashes($field);
$field = trim($field);
return $field;
}
//
}
$form = &NEW form_validation();
?>
i dont know what it is lol..no really, i forgot!.
lazy_yogi wrote:1. Class names generally start with upper case. In this case 'Text'
why? just cos someone else is doing it or is there some other reason for it? :?
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Re: Text Class

Post by Nay »

qads wrote: dont know where the hell i am at the moment.
Your outside ;)...

The code looks =\ imho. No indents and most of all......no heredoc? Er, nevermind that. I forgot some heredoc-ness too.

I took what lazy_yogi said and right now righting a class with some regular expressions for validation. E-mail and URLs included.

Though it's taking a while to get working =\

-Nay
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Post by qads »

yea i went there and the guy was like all ja.....hmmm...where am i? who are you people? oh god!...what you doing to my dog? PUT IT DOWN!!
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Re: Text Class

Post by lazy_yogi »

qads wrote:
lazy_yogi wrote:1. Class names generally start with upper case. In this case 'Text'
why? just cos someone else is doing it or is there some other reason for it? :?
It's a widely accepted convention in most OOP languages. Makes it easy to distinguish between classes and functions/variables

Nay wrote:The code looks =\ imho. No indents
yea... I prefer this syntax :

Code: Select all

if (...) {
    #do something
} elseif (...) {
    #do something else
} else {
    #do something else again
}
to

Code: Select all

if (...) 
{
#do something
}
elseif (...)
{
#do something else
} 
else
{
#do something else again
}
The first is not only less lines, but also more readable with the indenting.
Also white space between block statments are important to avoid that hard to read, cluttered look. So I have 2 lines betw functions and one line between each statment/block/if-else group/while loop/etc ...

Nay wrote:I took what lazy_yogi said and right now righting a class with some regular expressions for validation. E-mail and URLs included.

Though it's taking a while to get working =\

-Nay
Yea, I expect it'd be a bit fiddly to work.
I was thinking you could accept a regex as a string input and use exec() (if thats the right function in php - might be thikning of another language)

then one main problem is catching an error if the user puts in an invalid regex. and the other problem would be how to set the validity check in the class so that the class can execute it. Shouldnt be too hard tho with a bit of thought

Cheers,
Eli
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Re: Text Class

Post by McGruff »

What about a couple of simple library functions:

formSafe() - trim, htmlspecialchars. Makes values safe for a redisplayed form.
dbSafe() - escape string. Makes values safe for db.

(don't want to escape the string until have decided to process the submitted data rather than display the form, hence two fns)

I had an idea for a single class to validate all kinds of forms using a meta data array to define the name, type, validation fuction to run on each POST var, etc. Feed the class different meta data arrays for different forms, and it creates a report on failed regex/type tests, required keys not set, alien keys etc. The meta data arrays can get quite large however - maybe a "bad code smell".
Nay wrote:It's OOP fever for me now. I took a look at PHP5 and have gone w00t. I wish there was private and public methods with PHP4........or is there? ;).
I've never been bothered by this in php4. Private/public can work very well even if it's not enforced. In general I think the freedom php provides is a big plus.

Since the programmer is required to be a bit more organised, naming conventions can help. For example, you could prefix all private methods with a "_", and list them separately to the object interface methods.

Code: Select all

class MyClass
{
    // public (always try to make the interface crystal clear)
    var $public1;
    var $public2;
    var $public3;

    // list private properties only if it's helpful to do so (IMO)
    // - depends on the complexity of the class


    function setStuff()
    {

    }

    function setStuff2()
    {

    }

    function getStuff()
    {

    }

    function getStuff2()
    {

    }

    //////////////////////////////////////////////
    //              PRIVATE                     // 
    //////////////////////////////////////////////
    
    function _doSomething()
    {

    }

    function _doSomething2()
    {

    }

}
///////////////
// END CLASS //
///////////////
Small point: here and there some more descriptive names might be useful? Eg: $val and $values were confusing: what about $values_string and $values_array? Sounds niggly but I often spend a lot of time trying to name vars/fns etc well. Helps enormously to make the workings of the code clearer - and if you don't get it right first time it can be a nuisance to track down all the items you need to change later on.
Last edited by McGruff on Wed Aug 10, 2005 3:07 am, edited 1 time in total.
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Post by Nay »

Thanks for the tip(s) McGruff ;)...

Might I ask what difference does the _ make? Or it's just my stupidity that I did not get the:
McGruff wrote: and list them separately to the object interface methods.
I read, for PHP 5, they're Public, Private and Protected Functions. Public would mean the functions are as in PHP4, where you can call then in anyway. Private are only able to be called with $this-> and Protected can only be accessed with an class which extends one's class or itself.

Am I wrong or am I wong?

I just read the article at phpbuilder yesterday. Most of it made sense to me but I think I still have much to learn of the deeper rabbit hole of OOP in PHP, or even just OOP ways of that matter.

I would spend my cash on a book for PHP5 or OOP but too much flushed on this:

http://nokia.com/nokia/0,,47814,00.html

I guess a geek can never have enough of keyboard ;)

-Nay
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

The "_" is just a naming convention which makes it immediately obvious that the method is not intended to be accessed from outside the class.

The fns accessed from outside the class (eg getters and setters) are the objects interface - the services it provides. The rest of the workings of the object are hidden to the outside world (encapsulation).

Encapsulating complexity behind a simple interface is basically what OOP is all about. It's good to write up class def's to make it clear what bits are part of the interface and what bits are not. Hence the "private" comment - nothing underneath is intended to be accessed externally.

Must admit I've barely skimmed through the php5 specs as yet. Until 5 is widely installed on shared hosts, it's not going to be a lot of use to me. I'd rather not have to support two flavours of php ie with parallel versions of each OOP program.
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Good words of advice.
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

Image

(refresh 1-3 times if you don't see it, my server is wacky when it comes to image linking.. and if anyone has an idea why it does this, PM me! :P )
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

ack!

You brought this back from the dead! =P
Post Reply