Don’t Fear Exceptions

If you’re not one of the few, you surely get scared once you see one of these:

Fatal error: Uncaught exception ‘Exception’ with message ‘Not found’ in /home/usman/www/test.php on line 27

Fatal error: Uncaught exception ‘UnexpectedValueException’ in /home/usman/www/test.php on line 27

When you see Red or Orange screen with Exception you fear like you’ve committed a sin and just go back to code to repent. Congrats, you’re the majority.

What if I told you that Exceptions are no sin, rather blessings of object oriented programming?
What if I told you that an Exception doesn’t just mean that your code is wrong?

Let me show you how.

For example code, I am using Laravel PHP framework. But the knowledge is not Laravel specific. This article assumes that you know basics of Exception and how to catch it.

An Example

I believe in practical example, so rather than preaching, I am showing you a real life example.

It is really common, when a you search for an entry in database, you check if this entry exists. If not then you show an error.

$person = Person::find($id);

if (! $person) {
    // Show message: Person not found
}

// Person found
return View::make('person.show', compact('person'));

You handle this problem with an if everywhere, why? Why don’t you just throw an exception when something doesn’t exist? Do just this:

$person = Person::findOrFail($id); // Will throw an exception if not found
return View::make('person.show', compact('person'));

In just one place catch this error. For Laravel, put this in your app/start/global.php:

App::error(function(\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
    return 'Entry not found'; // You can show 404, or do whatever you want
});

If you’re not using Laravel then catch the exception using try-catch when you boot your application.

Advantages of Using Exceptions

An Exception is just what is not expected. Be fearless to throw an Exception whenever you think something is not expected and the function/method/application should stop executing further.

One of the big advantages of using Exception over traditional redirect, die/exit is that you separate your business logic from your transport layer(ex, HTTP).

For example, you use a direct HTTP redirect when a form validation fails. Now what if the end user is not using a browser at all, he is using your mobile app which uses the same business logic with an API? What if you’re unit testing? What if you’re firing a background job with CLI? No HTTP at all, now how?

You’re right, Exception. Create a class ValidationException which extends \Exception. And whenever a validation fails:

    throw new ValidationException('Hey kid, you forgot your name?');

Now catch this Exception:
In case of usual HTTP use, do a redirect.
In case of API, set a status code with JSON message perhaps.
In case of CLI, just dump the error message.

In the Example section above, you’ve seen another advantage. How we made our code simple and DRY(Don’t Repeat Yourself).
There are many other advantages, I’m not going over everything, please check this article if you’re not convinced.

In the end

I ask you one thing, please do yourself a favor, make use of object oriented best practices(like utilizing Exception) where it fits, you won’t regret. Our PHP community has been late in this regard, but the revolution is coming.

Please feel free to share your thoughts.

If you’re a Laravel developer then you may also like my model self-validating package with Exception – DRYVal.

Laravel 4 Uses Lots of Static, Not True.

Most of the time developers blame Laravel for using too much static. This claim is not true in case of Laravel 4, lets dig in and discuss why and how.

What is static?

In PHP you call it like this Class::$property.

As the name suggests, it preserves the state. Static variables preserve their values across the lifetime of the running application(in our case request). In a class if a static property is declared it becomes the property of the CLASS itself, NOT the property of the instance(s) of the class.

Why is static considered bad?

Well, there are debates. One of main reasons is, you can’t (quite) Mock a static variable or method as its difficult to override statics because the state is preserved and no object/instance is used. This makes it really difficult to Test(Unit Test) an application as Mocking is a must needed thing to unit-test an application fully.

When you start unit-testing your application then you will realize why static dependencies are so bad. It becomes quite impossible to replace implementations during testing. So you end up creating lots of hacks just for maintaining testability.

How does Laravel static work?

Laravel 4 doesn’t actually use static rather it mimics the static calling behavior. When you call a static method, actually much more things happen behind the scene than it appears. Lets go through the life cycle of a static call.

As an example we’re calling View::make('hello').
You will see literally there is no class View under the \ namespace. Rather Laravel uses aliases, so when you look at app/config/app.php, you will see View is just an alias of Illuminate\Support\Facades\View. So you’re actually calling:

Illuminate\Support\Facades\View::make('hello');

When we go to Illuminate\Support\Facades\View under (vendor/laravel/framework/src) we see just this code:

class View extends Facade {

	/**
	 * Get the registered name of the component.
	 *
	 * @return string
	 */
	protected static function getFacadeAccessor() { return 'view'; }

}

It extends the base Facade class, and in both classes there is no static method make(). The magic happens on the base Facade class, where there is a magic method __callStatic. This is called PHP Overloading, whenever you call a static method and this class doesn’t have that method then __callStatic is called(like a 404 page) with the called method name(‘make’) as the first parameter and the called parameters’ array as second parameter(array(‘hello’)).

What __callStatic does basically here, it calls the IoC Container binding with the name ‘view’ and calls the (non-static)method (‘make’) within it. What IoC Container contains, a pure instance of the original View class, in an object oriented way (not a class oriented way). So we can re-write the View::make('hello') as

$app->make('view')->make('hello')

Conclusion

Now we know Laravel makes it super easy to call methods which makes it look like static but actually its not, so we can easily mock the original View class and get our tests pass. Using these facades for static call is just a way to access Laravel classes, you can write your entire app without using these facades(static calls). Do you find anything incorrect, do you have something better to share? Please write in the comments.