Enforced disposal of objects in PHP.

v0.2.0 2021-10-19 16:03 UTC

This package is auto-updated.

Last update: 2024-04-19 21:50:48 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package provides a Disposable interface and using() global function that can be used to enforce the disposal of objects.

Installation

You can install the package via composer:

composer require ryangjchandler/using

Usage

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);

Handling Exceptions

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.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.