derywat/php-abortable

PHP library to manage aborting code execution.

Maintainers

Package info

github.com/derywat/php-abortable

pkg:composer/derywat/php-abortable

Statistics

Installs: 14

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.1 2026-02-18 15:06 UTC

This package is auto-updated.

Last update: 2026-02-18 15:10:54 UTC


README

Overview

Library allows aborting code by use of AbortController.

Usage

Abortable method in class

Implement abortable methods by using AbortableTrait in your class.
In places where it's safe to abort methods code, check for abort and exit or throw. AbortException may be used to abort any method and catch aborted state in caller code.

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.');
			}

		}

	}

}

Aborting from caller code

Using AbortController with single or multiple abort closures

Any number of abort closures may be added to AbortController. Abort closures will run every time when MyClass calls isAborted method.
Closure runs in the same process as abortable code. Returning true from closure will result in isAborted returning true. Catching AbortException allows to check if method was aborted.

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
}