dangoodman/deferred

Deferred callback execution based on RAII

1.0.1 2017-04-26 11:54 UTC

This package is auto-updated.

Last update: 2024-10-17 03:55:15 UTC


README

Build Status

Deferred

Deferred callback execution based on RAII.

Usage example:

    function download($url, $toFile)
    {
        // Temporary increase memory limit for this function
        // $restoreMemoryLimit automatically called upon function exit
        $prevMemoryLimit = ini_get('memory_limit');
        ini_set('memory_limit', '256M');
        $restoreMemoryLimit = new Deferred(function() use($prevMemoryLimit) {
            ini_set('memory_limit', $prevMemoryLimit);
        });

        $contents = file_get_contents($url);
        if (!$contents) {
            throw new \RuntimeException("Couldn't fetch url contents");
        }

        if (file_put_contents($toFile, $contents) === false) {
            throw new \RuntimeException("Couldn't save url contents to file '{$toFile}'");
        }

        return $contents;
    }

Compare it with following example without deferreds:

    function downloadWithouDeferred($url, $toFile)
    {
        $prevMemoryLimit = ini_get('memory_limit');
        ini_set('memory_limit', '256M');

        $contents = file_get_contents($url);
        if (!$contents) {
            ini_set('memory_limit', $prevMemoryLimit);
            throw new \RuntimeException("Couldn't fetch url contents");
        }

        if (file_put_contents($toFile, $contents) === false) {
            ini_set('memory_limit', $prevMemoryLimit);
            throw new \RuntimeException("Couldn't save url contents to file '{$toFile}'");
        }

        ini_set('memory_limit', $prevMemoryLimit);

        return $contents;
    }