Enforce the Disposal of Objects in PHP

Packages

October 22nd, 2021

php-using-featured.png

The using PHP package by Ryan Chandler enforces the disposal of objects in PHP. Inspired by Hack and C#, this package is useful when working with file handles:

The package contains a Disposable interface and a global using() function to ensure object disposal.

Given the following class in the readme:

1use RyanChandler\Using\Disposable;
2 
3class TextFile implements Disposable
4{
5 private $resource;
6 
7 public function dispose(): void
8 {
9 $this->resource = fclose($this->resource);
10 }
11}

The using() helper ensures the dispose() method is called even in the event of an exception via finally:

1// Simple `using()` implementation
2function using(Disposable $disposable, callable $callback): void
3{
4 try {
5 $callback($disposable);
6 } finally {
7 $disposable->dispose();
8 }
9}
10 
11// Example usage
12$file = new TextFile('hello.txt');
13using($file, function (TextFile $file) {
14 DB::create('messages', [
15 'message' => $file->contents(),
16 ]);
17});
18 
19// The `$resource` property is no-longer a valid stream,
20// since we closed the handle in the `dispose` method.
21var_dump($file->resource);

You can learn more about this package, get full installation instructions, and view the source code on GitHub. In C#, you can learn more about the using statement, which inspired this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.