PHP code example of phpgt / promise

1. Go to this page and download the library: Download phpgt/promise library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpgt / promise example snippets


// A simple operation with just a single "then":
$exampleSlowFileReader->read()
->then(function(string $contents) {
        echo "Contents of file: $contents", PHP_EOL;
});

// A more complex example, showing how promises can be chained together:
$exampleRemoteApi->getCustomerById(105)
->then(function(Customer $customer) {
        return $customer->loadLatestOrders(new DateTime("-5 weeks"));
})
->then(function(CustomerOrderList $orders) {
        echo "Customer {$orders->getCustomer()->getName()} ",
        "has made {count($orders)} in the last 5 weeks!", PHP_EOL;
})
->catch(function(Throwable $reason) {
        echo "There was an error loading the customer's details: $reason", PHP_EOL;
})
->finally(function() use($exampleRemoteApi) {
        $exampleRemoteApi->disconnect();
});

class Example {
// The class must keep a reference to its own Deferred object, as this will be
// referenced when the work completes in order to resolve its Promise.
        private Deferred $deferred;

// This public function will return a Promise representing the task's outcome.
        public function doTheTask():PromiseInterface {
// The Deferred is constructed with the process function as its only parameter.
                $this->deferred = new Deferred(fn() => $this->processFunction());
// The function returns the Deferred's promise.
                return $this->deferred->getPromise();
        }

// The process function will do one small piece of work each time it's called
// until the task is complete, at which point it will resolve the Deferred with
// the final value (from wherever it's calculated).
        private function processFunction():void {
                if($this->isThereMoreWorkToDo()) {
                        $this->doMoreWork();
                }
                else {
                        $this->deferred->resolve($this->getFinalValue());
                }
        }

        private function isThereMoreWorkToDo():bool { /* ... */ }
        private function doMoreWork():void { /* ... */ }
        private function getFinalValue() { /* ... */ }
}

$example = new Example();
$example->doTheTask()
->then(function($finalValue) {
        echo "Final value: ", $finalValue;
});