tags:

views:

75

answers:

3

It's really irking me that PHP considers the failure to instantiate an object a Fatal Error (which can't be caught) for the application as a whole. I have set of classes that aren't strictly necessary for my application to function--they're really a convenience. I have a factory object that attempts to instantiate the class variant that's indicated in a config file.

This mechanism is being deployed for message storage and will support multiple store types:

  • DatabaseMessageStore
  • FileMessageStore
  • MemcachedMessageStore
  • etc.

A MessageStoreFactory class will read the application's preference from a config file, instantiate and return an instance of the appropriate class.

It might be easy enough to slap a conditional around the instantiation to ensure that class_exists(), but MemcachedMessageStore extends PHP's Memcached class. As a result, the class_exists() test will succeed--though instantiation will fail--if the memcached bindings for PHP aren't installed.

Is there any other way to test whether a class can be instantiated properly? If it can't, all I need to do is tell the user which features won't be available to them, but let them continue one with the application.

Thanks.

A: 

If you use autoloading to load your class files (which you should), you can throw a custom Exception right at the end of your autoloader function(s) if the requested class in still not available for instantiation. This should trigger any time a non existing class is being used, even for PHPs internal classes. So it should trigger in your case.

Techpriester
Am I reading this wrong? From what I read, the ability to catch exceptions caught in the autoloader method only exists since 5.3. Sadly, I'm on 5.2.
Rob Wilkerson
It's also worth noting that I'm using a framework, so these classes are already included/defined. I assume this would by pass the autoloader method.
Rob Wilkerson
A: 

If your problem is to catch your Fatal Error you should try to write your own error handler and act accordingly to the error message. This way you can workaround you heritage problem with Memcache.

Maskime
A: 

As far as I can tell, this can't be done short of PHP 5.3. What I did instead was to make the factory class check for the existence of Memcached before instantiating the class that extends it. It's clumsy and far too brittle for my tastes, but it's working for now. When we upgrade to 5.3, I'll rework it a bit.

Rob Wilkerson