Enforced disposal of objects in PHP. 🐘
MIT License
This package provides a Disposable
interface and using()
global function that can be used to enforce the disposal of objects.
You can install the package via composer:
composer require ryangjchandler/using
You should first implement the RyanChandler\Using\Disposable
interface on your class. This contract requires an implementation of a public function dispose(): void
method.
class TextFile implements Disposable
{
private $resource;
public function dispose(): void
{
$this->resource = fclose($this->resource);
}
}
You can then use the using()
helper function with your Disposable
object to enforce disposal.
// This code might create a file pointer and store it on the class.
$file = new TextFile('hello.txt');
// We can then "use" the `$file` object inside of this callback. After the callback has been
// invoked, the `TextFile::dispose()` method will be called.
using($file, function (TextFile $file) {
DB::create('messages', [
'message' => $file->contents(),
]);
});
// The `$resource` property is no-longer a valid stream, since we closed
// the handle in the `dispose` method.
var_dump($file->resource);
The using()
function will wrap the invokation of your callback in a try..finally
statement.
This ensures that your object is disposed of regardless of any exceptions.
Any exceptions thrown inside of your callback will still propagate up to the top-level.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.