Defensive programming may sound like something your granddad did after the war, but it's key to reducing the number of bugs and increasing maintainability. We're going to look at what defensive programming is and some steps to doing it in PHP.
<a href='http://twitter.com'>click for drama</a> <script>console.log('boo!');</script>"; $after = strip_tags($before, "<br>"); "This is an example of<br> some html content!" # php.net/function.strip_tags
<a href='http://twitter.com'>click for drama</a> <script>console.log('boo!');</script>"; $after = htmlentities($before); "This is an example of<br> some html content! <a href='http://twitter.com'>click for drama</a> <script>console.log('boo!');</script>" # php.net/function.htmlentities
if (!($order instanceof Order)) { throw new InvalidArgumentException("Invalid order type"); } try { $this->api->send($order); } catch (ApiException $exception) { $this->logger->log("There was a problem sending an order"); throw $exception; } } if (!file_exists($templatePath)) { throw new InvalidArgumentException("Template not found"); } $template = file_get_contents($templatePath); return $this->renderer->render($template, $orders); }
$this->sendOrder($order); } } function validateOrders(array $orders) { foreach ($orders as $order) { if (!($order instanceof Order)) { throw new InvalidArgumentException("Invalid order type"); } }; } function sendOrder(Order $order) { try { $this->api->send($order); } catch (ApiException $exception) { $this->logger->log("There was a problem sending an order"); throw $exception; } }