Catching PHP Exceptions: Except the unexpected

PHP Exceptions can greatly assist in implementing various error scenario’s into an application. Before PHP5 one had to resort to specific return values or drastic measures like trigger_error(). Planning exceptions, I found out, is just as important as class design. At any point where a developer needs to handle the possibility of an exception being thrown he needs to know:

  • What Exceptions can I expect?
  • What Exceptions do I plan to catch?

In this post I’ll show some important aspects to consider when planning exceptions.

Keep reading

Controlled initialization of domain objects

In a recent project I’ve been working on, we have used the ‘Domain Model‘ to describe and design our application. Doing so we decouple persistency logic from the objects that are being passed around and modified throughout our application: The Domain objects. So what in MVC is often referred to as ‘model’ is actually a combination of a persistency layer, a service layer and a Domain layer. The persistency and service layer are also referred to as Data Access Objects: DAO. (As for the why and how of this architecture I recommend the article Writing robust backends with Zend Framework. For a good description of the DAO concept look here).

One of the challenges we were facing was that on one hand we wanted to implement business rules in our Domain objects. In plainish english: On setting or changing properties of the object (like changing a status) we want to validate if that action is allowed. On the other hand we want to be able to initialize an object to whatever state corresponds with the data fetched from the persistency layer. Doing so we found that the business rules got in the way during initialization when fetching it from the persistency layer. So what we were looking for was a way to allow the service layer to construct a Domain object using methods that are hidden from the rest of the code. We found two ways:

  1. Reflection (as of PHP 5.3)
  2. A design pattern where the Domain object initializes itself using the provided Service object.

Keep reading

Explicit PHP6?

Some days ago I read Fabien Potencier’s post ‘What for PHP 6’ pointing me to some features that might be implemented in PHP6. Two of those would have been nice in a project I’m currently working on where I’ve been experimenting with ‘domain objects’ having ‘scalar’ or ‘value’ objects as properties (more on that later). The first is scalar type hinting and hinted return values. The other is a __cast() method that replaces (or complements __toString()). Now that sounds quite java-ish and one of PHP merits is it’s flexibility but having the option to be more strict in my opinion is a good thing: If I feed my application with garbage I don’t blame it for being equally blunt.

Keep reading