Jump to content

Recommended Posts

I am quite thorough when it comes to programming, I always want to do things the most quick, efficient and 'well-respected' ways.  Often I come up with my own ideas but not nearly often enough...

My current problem is, what is the correct way to go about creating a user class and how does it integrate with session variables?

I mean, do I pass the user object within the sessions? Or do I load the user object from the session variables on every page?

Should I have a separate class that deals with sessions? Or should I just leave them open?

 

Thank you.

Link to comment
https://forums.phpfreaks.com/topic/114335-user-class-design/
Share on other sites

Hello Matthew,

 

I know this is the default answer - but it depends on the program you are writing.  To answer the question, though, I'll assume you're writing an application that requires user authentication and authorization - with role-based access security just for fun.  This application warrants the overhead of maintaining user authorization and state information in session, as it is required on every request.

 

If you are going to build the user object on each page request, it doesn't make sense storing the user data in raw format and manually building the user object on each page request.  Store the object directly in the session...but that requires a little planning:

 

When objects are serialized in session you must tell PHP which object parameters you wish to preserve.  Upon serialization, the __sleep() magic method is called on the object in question.  This method is expected to return an array of scaler parameter names that exists in the object that will be restored on unserialization.  These parameters will "magically" be restored when the session is started on the next page request.  Object parameters that hold special references to things like resources will not be preserved, however.  To restore these resources (db links, for example), you can restore them in the __wake() magic method, which is called when the object initialized from session. 

 

To things to note:

 

First - If your class aggregates other objects (an object is set as a parameter within the first), that class must also have a __sleep() method specified if you wish to restore the parameters.  You must manually serialize this object within the __sleep() method, and unserialize in the __wake() method, in order to handle this situation.

 

Second - In order to restore the object(s) you are serializing, the class must be defined prior to the session start.  This makes sense, of course, because if PHP doesn't know how to build the object, how can it restore it?  So, you need to include/require the class file prior to session start.

 

An example of what I mean:

 

The user object, that you will directly store in the session.

 

<?php

/**
* @see Role
*/
require_once "Role.php";

class user 
{
   
   /**
    * username
    * @var string
    */
protected $_username;

/**
 * userid
 * @var int
 */
protected $_userId;

/**
 * collection of user roles
 * @var Roles
 */
protected $_roles;

//getter, setter, and logic methods excluded

/**
 * prepare for serialization
 * 
 * this is the magic method we define which object parameters we want to preserve
 * 
 * note the aggregate object Roles
 * 
 * @return array
 */
public function __sleep ()
{

	//we have to serialize the object
	$this->_roles = serialize($this->_roles);

	$save = array 	(	'_username',
				      '_userId',
				      '_roles'
			      );

	return $save;
}

/**
 * restore from serialization
 * 
 * @return void
 */
public function __wake () {
	//restore the roles object
	//the roles class is included at the top of the User class
	$this->_roles = unserialize($this->_roles);
}

}
?>

 

The roles class that will be aggregated within the user object:

 

<?php

class Roles {

/**
 * role names - lets keep it simple
 * @var array of role names
 */
protected $_roles = array();

//getter, setter, and logic methods not included

/**
 * prepare for serialization
 * 
 * no need for a wake() method
 * 
 * @return array
 */
public function __sleep() {
	return array ('_roles');
}


}
?>

 

Finally, the simple storage of the user object:

 

<?php

//be sure to require the user class BEFORE session start
require_once "User.php";

session_start();

if (!isset($_SESSION['auth_user'])) {
//redirect to login, do logic, etc
}

if (!$_SESSION['auth_user']->hasRole('administrator')) {
//fake method on the User object demonstrates the operation on the object
//after session start
}
?>

 

Add some business logic to your User and/or role classes and your in business for a quick and dirty user object.

 

As a rule of thumb, keep your 'model' operations separate from your business logic.  In other words, keep persistent storage mechanics out of the domain model objects - pass the object to the object mapper for operations on the database, or to a session handler to handle thing like managing namespace of the session superglobal (again, if the situation dictates).

 

Hope this helps,

 

Steve

Link to comment
https://forums.phpfreaks.com/topic/114335-user-class-design/#findComment-588047
Share on other sites

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.