Jump to content

Recommended Posts

Hi!

 

I am developing a usermanagement module and I have stumbeled upon a crossroad on how I should setup my classes and design. I have created the following classes, User and DAO_User (not completed). Is this a good approach or is it just rubbish? (Unnecessary?) I would realy appreciate your opinions on this.

 

I am also trying to figure out where to put validation for userinput and the code for html. Any suggestions will be much appreciated.

- Should I create another class that displays the correct html?

- And another that takes care of validation?

- Or create f.ex: register.php which check for input, validates and displays the html

 

 

 

Below you will find examples of the three files.

 

User.php:

<?php
   class User 
{
	private $userID;
	private $username;
	private $password;

	public function __construct($userID, $username, $password)
	{
		$this->userID = $userID;
		$this->username = $username;
		$this->password = $password;
	}

	public function getUserID()
	{
		return $this->userID;
	}

	public function setUserID($userID)
	{
		$this->userID = $userID;
	}

	public function getUsername()
	{
		return $this->username;
	}

	public function setUsername($username)
	{
		$this->username = $username;
	}

	public function getPassword()
	{
		return $this->password;
	}

	public function setPassword($password)
	{
		$this->password = $password;
	}
}
?>

 

DAO_User.php:

<?php
/**
* @Klasse		DAO_User
* @Beskrivelse	
* 				
* @author 		
* @copyright 	
* @version		
*/

class DAO_User
{
	private $DB;	// Holds the database object

	/**
	 * Constructor
	 * 
	 * @param  Object db
	 * @return none
	 */
	public function __construct(Database $db)
	{
		$this->DB = $db;
	}	// End of constructor


	/**
	 * newUser()
	 * Creates a new user
	 *
	 * @param  String fname, lname, username, password, email
	 * @param  int level
	 * @return none 
	 */
	public function newUser($fname, $lname, $username, $password, $level = 0)
	{
		$fname = mysql_real_escape_string($fname);
		$lname = mysql_real_escape_string($lname);
		$username = mysql_real_escape_string($lname);
		$password = mysql_real_escape_string($password);
		$level = (int) $level;
		$query = sprintf("INSERT INTO users VALUES (0, '%s', '%s', '%s', sha1('%s'), '%s')", $fname, $lname, $username, $password, $level);
		$this->DB->query($query);
	}	// End of newUser()

	/**
	 * activateUser()
	 * Activates a user based on given userID 
	 * if it exists in system.
	 *
	 * @param  int userID
	 * @return none 
	 */
	public function activateUser($userID)
	{
		$userID = (int) $userID;
		$query = sprintf("UPDATE users SET level = 1 WHERE userID = %s", $userID);
		$this->DB->query($query);
	}	// End of activateUser()

	/**
	 * deleteUser()
	 * Deletes a user from the system based on userID
	 * if given userID exists in system.
	 *
	 * @param  int userID
	 * @return none 
	 */
	public function deleteUser($userID)
	{
		$userID = (int) $userID;
		$query = sprintf("DELETE FROM users WHERE userID = %s", $userID);
		$this->DB->query($query);			
	}	// End of deleteUser()


	/**
	 * updateUser()
	 * Updates a user
	 * 
	 * @param String fname, lname, username, password, email
	 * @param  int brukerID
	 * @return none 
	 */
	public function updateUser($userID, $fname, $lname, $username, $password, $email)
	{

	}	// End of updateUser()		

	/**
	 * getUser()
	 * Fetches a user based on userID
	 * if userID exists.
	 *
	 * @param  int userID
	 * @return array
	 */
	public function getUser($userID)
	{
		$userID = (int) $userID;
		$query = sprintf("SELECT userID, username, password FROM users WHERE userID = %s", $userID);
		$this->DB->query($query);
		$this->DB->fetch_row();
		$user = new User($this->DB->record['userID'], $this->DB->record['username'], $this->DB->record['password']);
		return $user;
	}	// End of getUser()		

	/**
	 * getNumUsers()
	 * Returns numer of users in system
	 *
	 * @param  none
	 * @return int 
	 */
	public function getNumUsers()
	{
		$query = "SELECT userID FROM users";
		$this->DB->query($query);
		$num = $this->DB->get_num_rows();
		return $num;
	}	// End of getNumUsers()

	/**
	 * getNumActiveUsers()
	 * Returns number of active users
	 *
	 * @param  none
	 * @return int 
	 */
	public function getNumActiveUsers()
	{
		$query = "SELECT userID FROM users WHERE level = 1";
		$this->DB->query($query);
		$num = $this->DB->get_num_rows();
		return $num;
	}	// End of getNumActiveUsers()

	/**
	 * getAllUsers()
	 * Returns all users in system as an array
	 * 
	 *
	 * @param  none
	 * @return array 
	 */
	public function getAllUsers()
	{
		$query = "SELECT userID, username, password FROM users";
		$tmp = array();
		$this->DB->query($query);
		while ($this->DB->fetch_row())
		{
			$tmp[] = new Bruker($this->DB->record['userID'], $this->DB->record['username'], $this->DB->record['password']);	
		}
		return $tmp;
	}	// End of getAllUsers()


}	// End of class DAO_User
?>

 

Example of register.php:

<?php	
if (isset($_POST['submit'])) 
{

	// Validate input
	if (ok)
	{
		// Register
	}
	else 
	{
		// Display htmlform with errors
	}

} 
else 
{
	// Display htmlform			
}
?>

Link to comment
https://forums.phpfreaks.com/topic/177799-how-to-design-my-usermodule/
Share on other sites

Why make user_id private if you can simply just get it by using one function (a getter)? Think about it.

Secondly, I usually put my validation code inside the class that it relates to. So I'd create a function called register() and another called login(). Makes it far easier to maintain.

 

  • 4 weeks later...

Thanks for your reply.

 

I have now put the validation in the User class. Changed the newUser method in DAO_User.php.

And modified the register.php. I have also created a new file / Class HTML_User where all html that's used for User is put.

 

User.php

<?php

/**
* Class: 		User
* Description:	
* 
* @author 		RK
* @copyright 	V1.2 - 09.11.2009
*/

class User 
{
	private $brukerID;
	private $first;
	private $middle;
	private $last;
	private $cell;
	private $email;
	private $username;
	private $password;
        
	private $level;
        private $ip;
        private $lastLoginn;
        private $dateRegistered;	

	private $errors;	

	/**
	 * Constructor - tmpUser
	 * Creates a new object of User without any info.
         * Used for registering a new user.
	 * 
	 * @params none
	 * @return none
	 */
	public static function tmpUser($errors)
	{
		$user = new Bruker();
		$user->errors = $errors;

		return $user;
	}

	/**
	 * Constructor - fullUser
	 * Creates an object of User with info.
	 * 
	 * @params String userID, first, middle, last, email, username, password, ip, lastLogin, dateRegistered
         * @params int cell, level
	 * @return none
	 */
	public static function fullUser($userID, $first, $middle, $last, $cell, $email, $username, $password, $level, $ip, $lastLogin, $dateRegistered)
	{
		$user = new Bruker();
		$user->userID           = $userID;
		$user->first            = $first;
            $user->middle           = $middle;
            $user->last             = $last;
            $user->cell             = $cell;
            $user->email            = $email;      			
		$user->username         = $username;
		$user->password         = $password;
            
		$user->level            = $level;
            $user->ip               = $ip;
            $user->lastLogin        = $lastLogin;
            $user->dateRegistered   = $dateRegistered;
            
		return $user;
	}

	/**
	 * getUserID
	 * 
	 * @params none
	 * @return int
	 */
	public function getUserID()
	{
		return $this->userID;
	}

	/**
	 * setUserID
	 * 
 	 * @params int userID
	 * @return none
	 */
	public function setUserID($userID)
	{
		$this->userID = (int)$userID;
	}

	/**
	 * getFirst
	 * 
	 * @params none
	 * @return String
	 */
	public function getFirst()
	{
		return ucfirst(strtolower($this->first)); 
	}

	/**
	 * setFirst
	 * 
	 * @params String first
	 * @return none
	 */
	public function setFirst($first)
	{
		if ( (ctype_alpha($first)) && (strlen($first) >= 2))
		{
			$this->first = $first;
			return true;
		} 
		else
		{
			$this->errors->setError('first', "Only letters are allowed!");
			return false;
		}
	}

	/**
	 * getMiddle
	 * 
	 * @params none
	 * @return String
	 */
	public function getMiddle()
	{
		return ucfirst(strtolower($this->middle)); 
	}

	/**
	 * setMiddle
	 * 
	 * @params String middle
	 * @return none
	 */
	public function setMiddle($middle)
	{
		if (!empty($middle))
		{
			if ( (ctype_alpha($middle)) )
			{
				$this->middle = $middle;
				return true;
			} 
			else
			{
				$this->errors->setError('middle', "Only letters are allowed!");
				return false;
			}
		}
	}

	/**
	 * getLast
	 * 
	 * @params none
	 * @return String
	 */
	public function getLast()
	{
		return ucfirst(strtolower($this->last)); 
	}

	/**
	 * setLast
	 * 
	 * @params String last
	 * @return none
	 */
	public function setLast($last)
	{
		if ( (ctype_alpha($last)) && (strlen($last) >= 2))
		{
			$this->last = $last;
			return true;
		} 
		else
		{
			$this->errors->setError('last', "Only letters are allowed!");
			return false;
		}
	}

	/**
	 * getCell
	 * 
	 * @params none
	 * @return int
	 */
	 public function getCell()
	 {
	 	return $this->cell;
	 }

	/**
	 * setCell
	 * 
	 * @params int cell
	 * @return none
	 */
	 public function setCell($cell)
	 {
	 	if ( (ctype_alnum($cell)) && (strlen($cell) ==  )
	 	{
	 		$this->cell = $cell;
	 		return true;
	 	}
	 	else
	 	{
	 		$this->errors->setError('cell', "Only numbers are allowed. 8 numbers.");
	 		return false;
	 	}
	 }
         
         /**
	 * getEmail
	 * 
	 * @params none
	 * @return String
	 */
	 public function getEmail()
	 {
	 	return $this->email;
	 }

	/**
	 * setEmail
	 * 
	 * @params String email
	 * @return none
	 */
	 public function setEmail($email)
	 {
            $email = filter_var($email, FILTER_SANITIZE_EMAIL);
	 	if ( (filter_var($email, FILTER_VALIDATE_EMAIL)) )
	 	{
	 		$this->email = $email;
	 		return true;
	 	}
	 	else
	 	{
	 		$this->errors->setError('email', "Email is not valid!");
	 		return false;
	 	}
	 }

	/**
	 * getFullname
	 * 
	 * @params none
	 * @return String
	 */
	 public function getFullname()
	 {
	 	return $this->getFirst. ' ' .$this->getMiddle(). ' ' .$this->getLast();
	 }

	/**
	 * getUsername
	 * 
	 * @params none
	 * @return String
	 */
	public function getUsername()
	{
		return $this->username;
	}

	/**
	 * setUsername
	 * 
	 * @params String username
	 * @return none
	 */
	public function setUsername($username)
	{
		if ( preg_match('[^a-zA-Z0-9_]', $username) )
		{
			$this->errors->setError('username', 'Letters, numbers and _ are allowed only');
		}
		else
		{
			$this->username = $username;
		}
	}

	/**
	 * getPassword
	 * 
	 * @params none
	 * @return String
	 */
	public function getPassword()
	{
		return $this->password;
	}

	/**
	 * setPassword
	 * 
	 * @params String password
	 * @return none
	 */
	public function setPassword($password, $password2)
	{
		if ( ($password == $password2) && (!empty($password)) )
		{
			$this->password = $password;
		}
		else
		{
			$this->errors->setError('pwd1', "Password field empty / Passwors does not match!");
			return false;
		}
	}

	/**
	 * printInfo
	 * 
	 * @params none
	 * @return none
	 */
	 public function printInfo()
	 {
	 	echo "Name: ".$this->getFullname().'<br />';
	 	echo 'Username: '.$this->getUsername().'<br />';		 	
	 }

}	// End of class User
?>

 

DAO_User.php

<?php
/**
* @Klasse      DAO_User
* @Beskrivelse   
*             
* @author       
* @copyright    
* @version      
*/

   class DAO_User
   {
      private $DB;   // Holds the database object
      
      /**
       * Constructor
       * 
       * @param  Object db
       * @return none
       */
      public function __construct(Database $db)
      {
         $this->DB = $db;
      }   // End of constructor
      
      
      /**
       * newUser()
       * Creates a new user
       *
       * @param  object user
       * @param  int level
       * @return none 
       */
      public function newUser(User $u)
      {
         $fname = mysql_real_escape_string($u->getFirst());
         $middle = mysql_real_escape_string($u->getMiddle());
         $lname = mysql_real_escape_string($u->getLast());
         $cell = mysql_real_escape_string($u->getCell());
         $email = mysql_real_escape_string($u->getEmail());
         $username = mysql_real_escape_string($u->getUsername());
         $password = mysql_real_escape_string($u->getPassword());
         $level = 0;
         $query = sprintf("INSERT INTO users VALUES (0, '%s' '%s', '%s', '%s', '%s', '%s', sha1('%s'), '%s', now(), '')", $fname, $middle, $lname, $cell, $email, $username, $password, $level);
         $this->DB->query($query);
      }   // End of newUser()
      
      /**
       * checkUsername
       * 
       * @params String username
       * @return boolean
       */
       public function checkUsername($username)
       {
            $username = mysql_real_escape_string($username);
		$query = sprintf("SELECT username FROM users WHERE username = '%s'", $username);
		$this->DB->query($query);
		$rows = $this->DB->get_num_rows();
		return ($rader == 0) ? true : false;
       }
      
      /**
       * activateUser()
       * Activates a user based on given userID 
       * if it exists in system.
       *
       * @param  int userID
       * @return none 
       */
      public function activateUser($userID)
      {
         $userID = (int) $userID;
         $query = sprintf("UPDATE users SET level = 1 WHERE userID = %s", $userID);
         $this->DB->query($query);
      }   // End of activateUser()
      
      /**
       * deleteUser()
       * Deletes a user from the system based on userID
       * if given userID exists in system.
       *
       * @param  int userID
       * @return none 
       */
      public function deleteUser($userID)
      {
         $userID = (int) $userID;
         $query = sprintf("DELETE FROM users WHERE userID = %s", $userID);
         $this->DB->query($query);         
      }   // End of deleteUser()
      
      
      /**
       * updateUser()
       * Updates a user
       * 
       * @param object User
       * @param  int brukerID
       * @return none 
       */
      public function updateUser(User $u)
      {
         
      }   // End of updateUser()      
      
      /**
       * getUser()
       * Fetches a user based on userID
       * if userID exists.
       *
       * @param  int userID
       * @return array
       */
      public function getUser($userID)
      {
         $userID = (int) $userID;
         $query = sprintf("SELECT userID, username, password FROM users WHERE userID = %s", $userID);
         $this->DB->query($query);
         $this->DB->fetch_row();
         $user = new User($this->DB->record['userID'], $this->DB->record['username'], $this->DB->record['password']);
         return $user;
      }   // End of getUser()      
      
      /**
       * getNumUsers()
       * Returns numer of users in system
       *
       * @param  none
       * @return int 
       */
      public function getNumUsers()
      {
         $query = "SELECT userID FROM users";
         $this->DB->query($query);
         $num = $this->DB->get_num_rows();
         return $num;
      }   // End of getNumUsers()
      
      /**
       * getNumActiveUsers()
       * Returns number of active users
       *
       * @param  none
       * @return int 
       */
      public function getNumActiveUsers()
      {
         $query = "SELECT userID FROM users WHERE level = 1";
         $this->DB->query($query);
         $num = $this->DB->get_num_rows();
         return $num;
      }   // End of getNumActiveUsers()
      
      /**
       * getAllUsers()
       * Returns all users in system as an array
       * 
       *
       * @param  none
       * @return array 
       */
      public function getAllUsers()
      {
         $query = "SELECT userID, username, password FROM users";
         $tmp = array();
         $this->DB->query($query);
         while ($this->DB->fetch_row())
         {
            $tmp[] = new Bruker($this->DB->record['userID'], $this->DB->record['username'], $this->DB->record['password']);   
         }
         return $tmp;
      }   // End of getAllUsers()
      
      
   }   // End of class DAO_User
?>

 

register.php

<?php

/**
* @author 
* @copyright 2009
*/

	error_reporting(E_ALL);

	require_once 'Database.php'; 
	require_once 'Errors.php';
	require_once 'User.php';
	require_once 'DAO_User.php';
    require_once 'HTML_User.php';

	$DB = new Database();
    $display = new HTML_User();

if (isset($_POST['submit']))
{
	$errors = new Errors();								
	$b = User::tmpUser($errors);						
	$b->setFirst($_POST['first']);
	$b->setMiddle($_POST['middle']);
	$b->setLast($_POST['last']);
	$b->setCell($_POST['Cell']);
        $b->setEmail($_POST['email']);
	$b->setUsername($_POST['username']);
	$b->setPassword($_POST['pwd1'], $_POST['pwd2']);

	$dao = new DAO_Bruker($DB);								


	if ($dao->checkUsername($b->getUsername()) == false)
	{
		$errors->setError('username', 'Username is already in use!');
	}

	if ($errors->isErrors())
	{
		echo "Errors found!";
		$errors = $errors->getErrors();

            $display->loginForm($errors);
	}
	else
	{
		$dao->newUser($b);
		echo "You are now registered!<br />";
		$b->printInfo();
	}
}
else
{
        $display->loginForm();
}
?>

 

HTML_User.php

<?php

/**
* @author 
* @copyright 2009
*/

    class HTML_User
    {


   function loginForm($errors="")
   {
	  echo <<<EOF

		<form action="register.php" method="POST">
		First: <input name="first" type="text" value="{$_POST['first']}" /> {$errors['first']} <br />
		Middle: <input name="middle" type="text" value="{$_POST['middle']}" /> {$errors['middle']} <br />
		Last: <input name="last" type="text" value="{$_POST['last']}" /> {$errors['last']} <br />
		Cell: <input name="cell" type="text" maxlength="8" value="{$_POST['cell']}" /> {$errors['cell']} <br />
            Email: <input name="email" type="text" maxlength="8" value="{$_POST['email']}" /> {$errors['email']} <br />
		Username: <input name="username" type="text" value="{$_POST['username']}" /> {$errors['username']} <br />
		Password: <input name="pwd1" type="password" /> {$errors['pwd1']} <br />
		Repeat Password: <input name="pwd2" type="password" /> <br />
		<input name="submit" type="submit" value="send" /> <br />
	</form> 
EOF;
   }
    
    }
?>

 

I get the following Notice error:

Notice: Undefined index: first in C:\xampp\htdocs\web\HTML_User.php on line 17

 

It's becuase the variabels used in the form are not set yet. How do i work around this?

 

I get the following Notice error:

Notice: Undefined index: first in C:\xampp\htdocs\web\HTML_User.php on line 17

 

It's becuase the variabels used in the form are not set yet. How do i work around this?

 

<?php
$first = isset($_POST['first']) ? $_POST['first'] : "";
...
First: <input name="first" type="text" value="{$first}" /> {$errors['first']} <br />
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.