2

This is a question about general performance through implementing the solution shown below. I am aware that this might be slightly opinion based, but I want to know if anyone has a clear idea as to if this is a good implementation, or if it should be solved in a better way.

This is just an example, but lets first create a class called Member. This will be instantiated multiple times when we are listing all Members in the database. Now, since in this example, this is an old and complicated system, every time the full list of members is shown, one member can be instantiated multiple times. So to reduce the entire operation of fetching the member every time, we cache the instantiated object in a static property of the class, and returns that if it already exists:

class Member {

    protected static $cachedMember = null;

    public static function get($id){
        if ( isset( self::$cachedMember[$id] ) ) return self::$cachedMember[$id];
        // If its not set, we fetch it from database...
        $obj = new static();    
        // Fetching member from database and applying the applicable values to $obj 
        // Then we set the filled $obj to the $cachedMember static. 
        self::$cachedMember[$id] = $obj;
        return $obj;
    }

}

Obviously, this will take up some memory, depending on how many times the Member class is instantiated with a unique member id. But this is released in turn when the script have ended (correct?). So as long as PHP has enough memory allocated, it's to my understanding no other downside to this implementation?

Ole Haugset
  • 3,709
  • 3
  • 23
  • 44
  • `static` is a reserved keyword. You cannot use `new static()`. – Syscall Feb 02 '18 at 10:07
  • 1
    @Syscall you can. See [New self vs. new static](https://stackoverflow.com/questions/5197300/new-self-vs-new-static) and [Late Static Binding](http://php.net/manual/en/language.oop5.late-static-bindings.php) – simon Feb 02 '18 at 10:23
  • @simon Thanks for this information. – Syscall Feb 02 '18 at 10:26

1 Answers1

2

Yes, that approach should work to avoid fetching a member with the same ID more than once from your database during the runtime of your script.

Yes, the memory is released when the script ends, but memory should not be a big issue here, since PHP is only storing a reference to each object in your static array, not the object itself.

One typo:
$obj = new self();

Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114
  • Thanks for the clarification, on only being referenced to an already initiated object. That didn't occur to me. And no, its not a typo :) See the link in the comments on the original question. Using new static(); is a valid way of doing it. – Ole Haugset Feb 02 '18 at 17:36
  • Happy to help. And thanks for the info about new static(). Always great to learn something new. – Erik Kalkoken Feb 02 '18 at 18:55