26

Safe PHP – Built-In Functions Rewritten to Throw Exceptions

 5 years ago
source link: https://www.tuicool.com/articles/hit/vi6JJrz
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In the project Safe PHP by David Négrier, all PHP functions that return false are rewritten to throw exceptions instead.

The readme describes the problem with functions returning false before exception handling came to PHP:

 Most PHP core functions have been written before exception handling was added to the language. Therefore, most PHP functions do not throw exceptions. Instead, they return false in case of error. 

The readme further goes on to explain what the code would look like to check for false using the current language capabilities:

$content = file_get_contents('foobar.json');
if ($content === false) {
    throw new FileLoadingException('Could not load file foobar.json');
}
$foobar = json_decode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new FileLoadingException('foobar.json does not contain valid JSON: '.json_last_error_msg());
}

The Safe PHP solution for this is as follows:

 Safe-PHP redeclares all core PHP functions. The new PHP functions are acting exactly as the old ones, except they are throwing exceptions properly when an error is encountered. The “safe” functions have the same name as the core PHP functions, except they are in the Safe namespace. 

Here’s what the function would look like using this package:

use function Safe\file_get_contents;
use function Safe\json_decode;

// This code is both safe and simple!
$content = file_get_contents('foobar.json');
$foobar = json_decode($content);

You can learn more about this repo and access the source code on GitHub . This package also has some automatic refactoring capabilities.

Note: The Safe PHP package is declared as experimenting, and has not reached 1.0 with some outstanding issues remaining .

This appeared first onLaravel News


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK