Often I construct a class something like this:

PHP Code:

require_once 'Validate.php'// PEARs validation class

class Contact {
  
  private 
$db;
  private 
$error = array();

  public function 
__construct($db) {
     
$this->db $db;
  }

  static function 
validate($var) {
     
// seems as if the class gets very dependent on Validate
     // and that Validate.php is included even often not needed.
     // of course I could move the require_once to here, but
     // that doesn't seem right either?

     
if (!Validate::uri($var['uri'])) {
        
$this->error['uri'] = 'error in uri';
     }
     if (empty(
$var['name'])) {
        
$this->error['name'] = 'name cannot be empty';
     }

     if (
sizeof($this->error) > 0) {
        return 
false;
     }
     return 
true;
  }

  public function 
save($var) {
     if (!
$this->validate($var)) {
        return 
false;
     }
     
// database logic

     
if (PEAR::isError($result)) {
        return 
false;
     }
     return 
true;
  }


I would have some test to test the whole thing.

PHP Code:

class ContactTestCase extends UnitTestCase {

   function 
testValidation() {
      
$this->assertFalse(Contact::validate(array('name'=>'')));
      
$this->assertFalse(Contact::validate(array('uri'=>'http://s')));
      
// and so on
   
}

   
// similar tests for the save mechanism


But when I wrote up the tests I just realised, that it seems my class is doing to much. However, I like to keep the validation close to the actual class, so it knows excactly what has to be validated before saving any thing, as most of my classes are used both from a web application, but also as a webservice through xmlrpc.

How do you go about structuring your classes and the validation before saving anything?