Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthew Weier O'Phinney:
Creating Exception types on-the-fly in modern PHP
Dec 07, 2018 @ 17:44:03

Matthew Weier O'Phinney has posted a tutorial to his site sharing a method he's found for creating Exception types dynamically allowing you to create a system that can still be caught by normal means but is more flexible than hard-coded exceptions.

We pioneered a pattern for exception handling for Zend Framework back as we initially began development on version 2 around seven years ago. The pattern looks like this: we would create a marker ExceptionInterface for each package. [Then] we would extend SPL exceptions and implement the package marker interface when doing so.

What this gave users was the ability to catch in three ways. [...] This kind of granularity is really nice to work with. [...] So, what happens when you're writing a one-off implementation of something that is expected to throw an exception matching one of these interfaces?

Why, use an anonymous class, of course!

He includes an example of putting this approach to work, using a throw call along with a dynamic (anonymous) class to extend the required class and implement the associated interface. In his example he creates a dynamic exception for handling a "not found" type of exception.

tagged: exception dynamic tutorial anonymous class custom

Link: https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html


Trending Topics: