ryangjchandler / using
PHP 中对象的强制销毁。
v0.2.0
2021-10-19 16:03 UTC
Requires
- php: ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- pestphp/pest: ^1.20
- phpstan/phpstan: ^0.12.99
- spatie/ray: ^1.28
README
此包提供了一个 Disposable
接口和 using()
全局函数,可以用来强制对象的销毁。
安装
您可以通过 composer 安装此包
composer require ryangjchandler/using
用法
您应该首先在您的类中实现 RyanChandler\Using\Disposable
接口。此合约要求实现一个 public function dispose(): void
方法。
class TextFile implements Disposable { private $resource; public function dispose(): void { $this->resource = fclose($this->resource); } }
然后,您可以使用 using()
辅助函数与您的 Disposable
对象一起强制执行销毁。
// 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);
异常处理
using()
函数会将您的回调调用包裹在一个 try..finally
语句中。
这确保了无论发生任何异常,您的对象都会被销毁。
在您的回调内部抛出的任何异常仍然会向上传播到顶层。
测试
composer test
变更日志
有关最近更改的更多信息,请参阅 CHANGELOG。
贡献
有关详细信息,请参阅 CONTRIBUTING。
安全漏洞
有关如何报告安全漏洞的详细信息,请参阅 我们的安全策略。
致谢
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。