0

Okay, I'm still very new to OOP overall, but I've created a few workable classes now and I'm slowly grasping the various concepts of OOP in PHP. On a project that I'm working on currently, a user can register, login/logout, and upload/delete/comment/rate images.

Currently, when a user logs in, I put most of their information (that I have retrieved from a database) inside the $_SESSION superglobal. This includes information such as their first name, username, user_id, etc.

Complementing this, I have a page called user.functions.php which has a number of miscellaneous functions that are related to the concept of a 'user', such as permissions checking, requesting additional user data, checking a successful login, registering a user, etc.

My question is how would I manage this as a User class? If I understand correctly, anything called on a page exists on that page only, so wouldn't I have to declare a

new User();

on each page where I need to perform a task relating to that user? How is that in anyway efficient? Isn't it just simpler to call a function like:

changeAddress();

instead of:

$user = new User();
$user->changeAddress();

What about critical user data such as the user_id, which I currently store in a session? Would I migrate that data inside a class too and retrieve it via a getter method?

Basically, I fail to see how the concept of a user object can improve overall code quality, if a user, which is an inherently cross-page concept, is tied to an object, which exists solely within the confines of a single document?

What am I missing here?

marked-down
  • 9,958
  • 22
  • 87
  • 150
  • If you want user data to persist after a session has expired, you need to save it to a file or database. –  Aug 25 '13 at 06:33
  • See this post about storing objects in the session http://stackoverflow.com/questions/132194/php-storing-objects-inside-the-session – chiliNUT Aug 25 '13 at 06:34

2 Answers2

0

rather than putting all the information individually in the $_SESSION you can store a $user object in session so you can access the user object from any page.

$_SESSION['user'] = new User();
$_SESSION['user']->changeAddress();
DevZer0
  • 13,433
  • 7
  • 27
  • 51
0

You are dealing with two different different concepts:

  • Encapusulation of user related functionality in a class.
  • The stateless nature of the http protocol that causes all information to be lost after a request - response cycle is complete, except for session information that might be preserved between requests through various mechanisms.

As such, the fact that you have to recreate objects or actually any variables will happen no matter what. Creating an object of some class should not cost much. Populating the members is what counts. Following a non-OO methodology would result in populating individual variables instead of members of a class with no gain in performance.

Tarik
  • 10,810
  • 2
  • 26
  • 40