0

If I do this in PHP 5.x (generally pseudo-code):

class object{
    __construct($id){
       <<perform database query>>
    }
}

$array(1) = new object(1);
$array(1) = new object(1);

Am I wasting efforts (memory, cpu, etc)? Will the database query run twice?

What is the best way to avoid this (if it's a concern)? Using $array(1) instanceof object? isset($array(1))? array_key_exists(1, $array)?

Is there a (good?) way to check in the class to see if it already exists before it does all the work again?


EDIT: For clarity, I do not need this object twice. And this object will be used again $array(523) = new object(523); My main question is how best to avoid redundantly creating the exact same object.

MECU
  • 770
  • 1
  • 11
  • 25
  • re your last sentence, read up the singleton pattern – Prisoner Dec 12 '12 at 17:14
  • 5
    Don't do database operations in __construct() – v0d1ch Dec 12 '12 at 17:14
  • 2
    What @vodich said. And **don't** read up on the singleton anti-pattern. Maintaining a single DB connection is good. Using a `Singleton` for that purpose, however, should be avoided. –  Dec 12 '12 at 17:17
  • I'm confused here. Do you need two different objects or not? – raina77ow Dec 12 '12 at 17:18
  • What is wrong with Singletons, @rdlowrey? – Michael Dec 12 '12 at 17:19
  • @raina77ow I do not need 2 different objects. While going through my code, I'm currently just declaring new object(1) (for example) without checking if it already exists. I want to know if it's doing anything, or it somehow already goes "Hey, this already exists, don't bother." – MECU Dec 12 '12 at 17:20
  • @vodich Then how (best) should I populate the information needed for my object? – MECU Dec 12 '12 at 17:21
  • 2
    Create a Factory with a cache, which returns existing objects and only creates them when not instantiated. – Wrikken Dec 12 '12 at 17:29
  • @MichaelRushton They're death to testability, they promote tight coupling and they carry around state for the life of the application: http://stackoverflow.com/a/138012/895378 ... There remains a very small, very misguided minority that clings to the idea that `Singleton` isn't harmful. IMHO, there's no way those people are unit testing their code correctly. Inversion of control is vastly preferable. –  Dec 12 '12 at 17:32

1 Answers1

3

If you want to avoid creating multiple objects, you have a few choices. The ones that come to mind are...

  1. Create the object once and ensure it's passed to where it's needed. This means you'll have to check the dependencies in your code with respect to that object.

  2. Use an object factory to construct the object and it can return a reference to the object rather than creating a new one, if it was already created.

  3. Implement the singleton pattern.

As with everything else, trade-offs obtain, so check your situation and decide what is the most appropriate for you.

RonaldBarzell
  • 3,822
  • 1
  • 16
  • 23