Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/liamja/defer
PHP library to postpone the calling of a function or callable.
https://github.com/liamja/defer
composer-library composer-package php php5 php53 php54 php55 php56
Last synced: about 2 months ago
JSON representation
PHP library to postpone the calling of a function or callable.
- Host: GitHub
- URL: https://github.com/liamja/defer
- Owner: liamja
- Created: 2018-02-18T17:28:06.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2018-02-18T17:39:09.000Z (almost 7 years ago)
- Last Synced: 2024-10-13T12:20:14.064Z (3 months ago)
- Topics: composer-library, composer-package, php, php5, php53, php54, php55, php56
- Language: PHP
- Homepage:
- Size: 6.84 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# 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
```php
// Create an instance of Defer.
// When $defer falls out of scope, the deferred callables will be called in reverse order.
$defer = new Defer;// Push your deferred tasks to the $defer object.
$defer->push(function () {
echo "I'm echoed last!";
});// As a convenience, you can also call $defer as a function
$defer(function () {
echo "I'm echoed second!";
});echo "I'm called first!";
```### Closing Resources
Defer can be used for ensuring the closing of open files:
```php
$fp = fopen('/tmp/file', 'w');$defer(function () use ($fp) {
fclose($fp);
});fwrite($fp, 'Some temporary data.');
```