PHP code example of derywat / php-abortable

1. Go to this page and download the library: Download derywat/php-abortable 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/ */

    

derywat / php-abortable example snippets


use derywat\abortable\AbortableInterface;
use derywat\abortable\AbortableTrait;

class MyClass implements AbortableInterface {
	use AbortableTrait;

	protected function myAbortableMethod(){

		while($codeRuns){

			/* 
			 *  some code block that cannot be aborted
			 */

			//check conditions and abort in places where it's safe to abort
			if($this->isAborted()){
				//do some cleanup and abort execution

				//AbortException can be used to abort execution and catch in caller
				throw new AbortException('abort request received.');
			}

			/* 
			 *  some code block that cannot be aborted
			 */

			//check multiple times if needed...
			if($this->isAborted()){
				//do some cleanup and abort execution
				throw new AbortException('abort request received.');
			}

		}

	}

}

use derywat\abortable\AbortController;
use derywat\abortable\AbortException;

$instance = new MyClass();

$instance->registerAbortController(
	(new AbortController())
		->addClosure(
			function():bool {
				//check conditions for abort
				//return true if code should abort
				//false otherwise
			}
		)
		->addClosure(
			function():bool {
				//another closure...
			}
		)
);

//running abortable method
try {
	$instance->myAbortableMethod();
	//myAbortableMethod returns to here if not aborted
} catch(AbortException $e){
	//this code runs if myAbortableMethod was aborted
}