Jump to content

Basic OOP question: using classes in multiple files


kn0wl3dg3

Recommended Posts

This may sound like a very stupid question, but I can't find a clear answer anywhere.

 

I'm making my first dive in OOP and all the tutorials only really show basic usage. They define a class, and show how to use it in a file.

 

My question is how does it work to use an object throughout a program? Is it available everywhere or do I store things in sessions and start a new object on each page?

 

For example: logging in a user. If I created an instance after confirming the credentials, would that same instance be available for use in say index.php, or would I just pass a session over and create a new instance on each page?

 

Again, sorry if this seems dumb to some people.

Link to comment
Share on other sites

You would create a session with whatever data you need to recreate the object and then do so, php itself does not store the object. You CAN serialize an object and store it in a session and then deserialize it, but I do not recommend doing so. Usually if it is a lot of information you would store it in a database and then store the primary key in a session and create a function in the class which will reset its objects based on the DB info.

Link to comment
Share on other sites

@ajlisowski:

You would create a session with whatever data you need to recreate the object and then do so, php itself does not store the object. You CAN serialize an object and store it in a session and then deserialize it, but I do not recommend doing so.

 

I get that. That's what I thought the answer would be. I'll look into serializing, but only with an educational mindset :)

 

Usually if it is a lot of information you would store it in a database and then store the primary key in a session and create a function in the class which will reset its objects based on the DB info.

 

This wasn't about any particular issue I'm having, but I do use dbs for that, so I appreciate the advice.

 

Can you clarify what you mean here?

create a function in the class which will reset its objects based on the DB info.

 

@Muddy_Funster

It wasn't really any particular issue, just wondering how it's done. Basically it was the login scenario that started the line of thought. Do I write in a login method, only to instantiate a user class in the login page just to call that one method, store a session and pass it over to another script that instantiates another class? Do I skip all that login stuff, do it proceduraly, and make the class once I get where the info is needed? Those kind of thoughts started flying through my mind so I asked :)

 

Thanks for the replies to both of you

Link to comment
Share on other sites

I'm still not clear, are you trying to access a class over multiple pages or are you simply looking to make a value available to multiple pages?

 

Sorry.

 

Access a class over multiple files. Just wondering how it's usually handled. Is there a way, or do you just remake the class on each page.

Link to comment
Share on other sites

You can also use the singleton pattern to make sure you don't create multiple instances of the same class all over the place. For instance if I was to create a user object when someone logs into a website you don't want to be creating multiple instances of the same class for a single user.

 

<?php
class Foobar {
        public $name;	

private static $instance = NULL;	

public static function get_instance() {
	if(self::$instance === NULL) {
		self::$instance = new self();	
	}
	return self::$instance;
}

public function __construct() {
}
}
?>

 

So instead of

 

<?php
/*
2 different objects $x is overwritten
*/
$x = new Foobar();
$x->name = "Joe";
print "My name is: ".$x->name."<br />";

$x = new Foobar();
print "My name is: ".$x->name."<br />";
?>

 

We can do

 

<?php
/*
$x is the same object
*/
$x = Foobar::get_instance();
$x->name = "Fred";
print "My name is: ".$x->name."<br />";

$x = Foobar::get_instance();
print "My name is: ".$x->name."<br />";

?>

Link to comment
Share on other sites

Ok, I just read that link.

 

Correct me if I'm wrong:

Autoloading takes away the nuisance of including a bunch of classes, correct?

 

Correct.  It's the mechanism that makes OOP in PHP relatively painless.

 

Ok, got it.

 

Unfortunately, I don't think that's what I'm after (or at least I don't recognize it as such)

 

I'm sorry for all the confusion guys, I guess I don't know how to word what I'm looking for.

 

I was more curious about using a single instance of a class throughout several scripts. Is this something I'm missing in autoload?

Link to comment
Share on other sites

Personally, I have never implemented anything to try and "pass" an object from page load to page load. I just create the objects on each page load as needed.

 

You stated an example of a class to log in a user. Why would you even need to reuse that object as the user moves from page to page. If they are logged in, you shouldn't need to even load that class or reuse the object from when they logged in. Simply set a session variable then check if that session var exists on page load. If yes, continue on with the code to display the requested page. If not,then initiate the login class.

 

if(!isset($_SESSION['gogged_in']))
{
    include('user_login_class.php');
    $login_object = new login_class();
    // etc
}
else
{
    //display page
}

Link to comment
Share on other sites

Personally, I have never implemented anything to try and "pass" an object from page load to page load. I just create the objects on each page load as needed.

 

You stated an example of a class to log in a user. Why would you even need to reuse that object as the user moves from page to page. If they are logged in, you shouldn't need to even load that class or reuse the object from when they logged in. Simply set a session variable then check if that session var exists on page load. If yes, continue on with the code to display the requested page. If not,then initiate the login class.

 

I must be way off on my thinking here. I just thought it was problem-prone to recreate the same object on every page. A user was a good example I thought because parts of they're info would potentially be used all over the place, so making one instance that's available all over seemed beneficial.

 

But you're suggesting using a session variable to store an id (for example), then on every page, recreate that object by going into the db and getting all the info connected to id? Doesn't that seem redundant? And that's what I'm wondering about.

 

Again, maybe I'm not getting something obvious. Thanks for taking the time to try to help.

Link to comment
Share on other sites

In an example a single user object would be stored in a session when a user logs into a website. The object will persist throughout the website. The fact it is a singleton means that multiple instances of the same class cannot be created.

 

Ok, that makes sense. I'm doing some reading on singletons right now, thanks.

Link to comment
Share on other sites

But you're suggesting using a session variable to store an id (for example), then on every page, recreate that object by going into the db and getting all the info connected to id? Doesn't that seem redundant? And that's what I'm wondering about.

 

Why would you need to recreate the object. Do you need ALL the info for the user on every page load or wouldn't you just need the user ID. Besides, relying upon "variable" data from a previous page load on a subsequent page load can be dangerous. Take the example of a user. If you were to pull a user's permissions on a previous page load and stored that as the user navigates from page to page, then the user's permission wouldn't be updated if an administrator made changes until the user logged out and back in.

 

FYI: This is from the manual under design patterns (http://php.net/manual/en/language.oop5.patterns.php)

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

 

I'm not arguing that singleton's should or should not be used, just that the objects are typically specific to the request (i.e. page load). Again, I would go back to my previous question of why you need the user object created during login on each page load. Typically after the user logs in you would be using other objects for the user to work with different records.

Link to comment
Share on other sites

Why would you need to recreate the object. Do you need ALL the info for the user on every page load or wouldn't you just need the user ID. Besides, relying upon "variable" data from a previous page load on a subsequent page load can be dangerous. Take the example of a user. If you were to pull a user's permissions on a previous page load and stored that as the user navigates from page to page, then the user's permission wouldn't be updated if an administrator made changes until the user logged out and back in.

 

I get what you're saying, I think. And I hope you don't think I'm being argumentative, I swear I'm not. Just ignorant I guess  :D

 

It's not an issue of needing to do something specific right now. I just started to wonder how it worked.

 

Say Joe logins in to the website. On a successful login it would redirect him to the home page where it says "Welcome Joe". I would need an instance of the User class there to use a method named getName..correct?

 

Now say he navigates to a preferences page or something where he can fill in a bunch of details. A new instance would need to be created here also, if I understand correctly. That's where my question comes in. Since it's the same user (and therefore in my mind the same instance of joe) I was wondering how that already created class would go with him, but you're saying it wouldn't. I would need to create a new instance on every page, if I understand you.

 

And I think you're also making the point that the data would then be updated every time you create that new instance instead of having potentially old data following the user. My worry was that creating all these new instances would lead to data anomalies, but I'm taking it that I shouldn't be concerned if I'm using a database.

 

Am I following?

 

And I have no idea what any of this means :P

FYI: This is from the manual under design patterns (http://php.net/manual/en/language.oop5.patterns.php)

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

 

I'm not arguing that singleton's should or should not be used, just that the objects are typically specific to the request (i.e. page load). Again, I would go back to my previous question of why you need the user object created during login on each page load. Typically after the user logs in you would be using other objects for the user to work with different records.

 

Manual, here I come

Link to comment
Share on other sites

Objects can be passed from page to page via sessions.  Remember: object = particular instance of a class.  So, if Forrest Gump logs in, and you store that Forrest Gump object in sessions, that one Forrest Gump object will move from page to page.

 

And, really, forget about singletons.  They're dangerous (they're really nothing more than global variables), and there's usually a better way to solve a problem than using them.  They have their uses in rare occasions, but they cause most programmers to cringe.

Link to comment
Share on other sites

Objects can be passed from page to page via sessions.  Remember: object = particular instance of a class.  So, if Forrest Gump logs in, and you store that Forrest Gump object in sessions, that one Forrest Gump object will move from page to page.

 

Ok, I get that.

 

Would all the methods and properties be accessible in the same way? (ex.$user->getName() to get users name)

 

And, really, forget about singletons.  They're dangerous (they're really nothing more than global variables), and there's usually a better way to solve a problem than using them.  They have their uses in rare occasions, but they cause most programmers to cringe.

 

Understood.

Link to comment
Share on other sites

Yes, if you store the object in the session it should act exactly as how it did before hand. Others have mentioned autoloading but its important to note that if you store an object in a session it either needs to be autoloaded or the class of the object needs to already have been defined by the time session_start() is called.

 

Personally I never store objects in a session. For a user I would just store the ID of the user and have some piece of code run that would recreate the object based on that ID whenever it is needed (or even automatically on every page, but that's the benifit of having a single point of access). OO in php is a bit hard to grasp coming from C++ and the like specifically because of the fact the objects are not carried throughout the session.

 

create a function in the class which will reset its objects based on the DB info.
By this I just meant a function that will take the ID of the object and grab data from the DB and set the various variables within the class.

 

 

 

Link to comment
Share on other sites

Yes, if you store the object in the session it should act exactly as how it did before hand. Others have mentioned autoloading but its important to note that if you store an object in a session it either needs to be autoloaded or the class of the object needs to already have been defined by the time session_start() is called.

 

Personally I never store objects in a session. For a user I would just store the ID of the user and have some piece of code run that would recreate the object based on that ID whenever it is needed (or even automatically on every page, but that's the benifit of having a single point of access). OO in php is a bit hard to grasp coming from C++ and the like specifically because of the fact the objects are not carried throughout the session.

 

create a function in the class which will reset its objects based on the DB info.
By this I just meant a function that will take the ID of the object and grab data from the DB and set the various variables within the class.

 

 

 

 

Ok, gotcha

Link to comment
Share on other sites

I'll throw in my two cents here as well.

 

You DON'T want to pass an object from one page to another using sessions or any other means. The web is stateless, and was designed to be that way. If we want to make it stateful, we must do so carefully, using as little information as possible.

 

In your example, if you want the user class to exist through all of your scripts, you want to re-initiate it on each request. You won't lose any data, because with PHP, you can use sessions to pass the user's ID (this should be static, therefor it will never be stale data) to any script that needs it. You can then pass this ID to the user class when you initiate it, and all of your data will exist again.

 

This method is actually FASTER than serializing the object, throwing it into a flat-file session, de-serializing it, and re-initiating it. Storing it in the session also causes your data to be stale, as the information in the serialized object may not reflect that in the database.

 

You want to recreate objects with each request. Use sessions or some other token system to pass the IDs your objects need to rebuild themselves into the previous state they were.

 

Hope this helps.

Link to comment
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.