项目作者: liamja

项目描述 :
PHP library to postpone the calling of a function or callable.
高级语言: PHP
项目地址: git://github.com/liamja/defer.git
创建时间: 2018-02-18T17:28:06Z
项目社区:https://github.com/liamja/defer

开源协议:

下载


Defer

Postpone the calling of a function or callable.

Why?

From Go by Example:

Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup.
defer is often used where e.g. ensure and finally would be used in other languages.

Common use cases are:

  • Cleaning up temporary files.
  • Closing network connections.
  • Closing database connections.

Comparing defer to finally, this implementation of defer will allow us to have better control over when our
deferred functions are called; we can decide when to start stacking deferred functions, and where to finally call them.

Examples

Usage

  1. // Create an instance of Defer.
  2. // When $defer falls out of scope, the deferred callables will be called in reverse order.
  3. $defer = new Defer;
  4. // Push your deferred tasks to the $defer object.
  5. $defer->push(function () {
  6. echo "I'm echoed last!";
  7. });
  8. // As a convenience, you can also call $defer as a function
  9. $defer(function () {
  10. echo "I'm echoed second!";
  11. });
  12. echo "I'm called first!";

Closing Resources

Defer can be used for ensuring the closing of open files:

  1. $fp = fopen('/tmp/file', 'w');
  2. $defer(function () use ($fp) {
  3. fclose($fp);
  4. });
  5. fwrite($fp, 'Some temporary data.');