PHP code example of needle-project / process-transaction
1. Go to this page and download the library: Download needle-project/process-transaction 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/ */
needle-project / process-transaction example snippets
mentService = new class {
public function chargeMoney() {
// your logic
echo "Customer has been charge!\n";
}
public function refund() {
echo "Customer has been refunded!\n";
}
};
$stockReservationService = new class {
public function reserveStock() {
echo "Could not reserve stock!\n";
throw new \Exception("The trigger of failed process");
}
};
$charge = new \NeedleProject\Transaction\Process(
function () use ($paymentService) {
return $paymentService->chargeMoney();
},
function () use ($paymentService) {
return $paymentService->refund();
},
'Payment Actions'
);
$reserveStock = new \NeedleProject\Transaction\Process(
function () use ($stockReservationService) {
return $stockReservationService->reserveStock();
},
function () {
echo "This will not be executed!\n";
},
"Stock Reserve"
);
// Processing an order
$executor = new \NeedleProject\Transaction\Executor();
$executor->addProcess($charge);
$executor->addProcess($reserveStock);
// Executing the processes
try {
$executor->execute();
} catch (\Exception $e) {
$executor->rollBack();
}
// Getting the process result
echo $charge->getExecutionResult() . "\n";
echo $reserveStock->getRollBackResult() . "\n";