Knowledgebase

Portal Home > Knowledgebase > Articles Database > PHP singleton class structure - Am I doing it right ?


PHP singleton class structure - Am I doing it right ?




Posted by bilalghouri, 09-07-2010, 09:12 PM
I have a really big script. It has a database class, a base class, a user authentication class, a resellers authentication class, paypal ipn class, a downloads class, and a plugins class The Base class extends database class like this: And I call my code like this : I think the structure is really bad. Thats why I want to implement singleton method. how can I achieve this ? Please help. Last edited by bilalghouri; 09-07-2010 at 09:19 PM.

Posted by TonyB, 09-07-2010, 09:53 PM
First thing I need to ask is what PHP version are we working with here? You don't use __construct() for the constructors. You also make use of var $variable which is deprecated in PHP5. So I'm not sure based on the version being used what to recommend. I'm also not sure what you're trying to accomplish here. If it's all of them share the same database instance it's not well designed. For one if you were to initialize a database connection each time it would have it's own separate object. So it would be inefficient. The point of a singelton is to create one object/resource and pass it along your application without having to recreate it. So something like this would accomplish it: Hopefully that helps I think the code is right. I would not recommend using this method though. So for example I'd much prefer doing this and lets assume the Database portion is like I had above as instance portion does not matter. It makes the code much more modular. It's really just a matter of getting the objects initialized somewhere. Once they are it's generally trivial in a web application to pass the ones that depend on each other. The base class you could still use although it would serve an entirely different function so for example here: So does that help at all? I think I got all the code right there. Last edited by TonyB; 09-07-2010 at 09:59 PM.

Posted by bilalghouri, 09-07-2010, 11:46 PM
Thanks for your helpful reply. The version I am using is 5.3.2 All of them are supposed to share the same instance. $mydb = Database::getInstance(); I would prefer not to create the database instance from outside the class. I want it to work like this : how can I accomplish that kind of structure? And is it possible to pass around the $this -> config variable from the Base class to all the child classes which extend it, for example the users class. and I had a long break from coding .. so I couldnt catch up with all the changes in php5, thats the reason I didnt know var $variable was deprecated.

Posted by bilalghouri, 09-12-2010, 06:59 AM
hello? any help please?



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
GeoIP with HAproxy? (Views: 571)


Language:

Contact us