Avoid an endless pifall - Blog - Open Source - schlitt.info

schlitt.info - php, photography and private stuff

Avoid an endless pifall

During my current exam phase I'm working on some tiny private project to relax after learning. In there I'm using a main controller class, which implements a singleton pattern and initializes several sub-controllers while being created. The singletons purpose is, that the other controllers can access to main controller and its functionality whenever they need, without storing a reference each. The code for the singleton looked about like this:

class tsMainController { private static $instance; public static function getInstance() { if ( self::$instance === null ) { self::$instance = new tsMainController(); } return self::$instance; } private function __construct() { $this->subController1 = new tsSubController1(); $this->subController2 = new tsSubController2(); // ... } }

What I experienced last night was quite annoying: Instead of my little app starting as usual, it spit out error over error in an endless loop. A few debugging minutes later, I found the suspicious code piece in one of the sub controllers:

class tsSubControllerX { public function __construct() { tsMainController::getInstance()->doSomething(); // ... } }

Basically, the sub controllers constructor accessed the main controllers singleton method, which is quite the purpose of it. But since the main controller itself did not finish its constructor, yet, the singleton method did not find a valid instance and started creating a new one. This step again created a new instance of tsSubControllerX and so on. I simply moved the construction code of the main controller into a new initialization method, so that the instance is ready before the sub controllers get instanciated.

So, whenever you mess around with lots of nested objects and a singleton, beware of this (absolutely logical) issue. I guess some of you already shared this experience, although in PHP web application environments you usually avoid such deeply nested object structures, but you possibly don't in other environments. ;)

If you liked this blog post or learned something, please consider using flattr to contribute back: .

Trackbacks

Comments

Add new comment

Fields with bold names are mandatory.