PHP code example of php-unified / state
1. Go to this page and download the library: Download php-unified/state 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/ */
php-unified / state example snippets
$output = [
'packages' => '',
'states' => [
'name' => 'php-unified/state',
'version' => '1.0.0'
]
]
use PhpUnified\State\State;
use Application\Database\Connection;
use Application\Logger\Logger;
$systemState = new State();
$systemState->setIdentifier('system-state');
$databaseTransactionState = new State();
$databaseTransactionState->setIdentifier('last-db-transaction-state');
$systemState->addState($databaseTransactionState);
$logger = new Logger();
$connection = new Connection($databaseTransactionState);
try {
$connection->doQuery();
} catch (Throwable $e) {
$logger->log('warning', $e->getMessage());
$logger->info($systemState->__toString());
}
namespace Application\Database;
use PhpUnified\State\Common\StateInterface;
class Connection
{
/**
* State tracker
*
* @var StateInterface
*/
private $state;
/**
* Constructor
*
* @param StateInterface $state
*/
public function __construct(StateInterface $state)
{
$this->state = $state;
}
/**
* Fictional doQuery function
*
* @return void
*/
public function doQuery(): void
{
$state->setValue('Starting database connection');
$connection = connectToDatabase();
$state->setValue('Starting transaction');
$connection->startTransaction();
$state->setValue('Executing transaction');
if($connection->doTransaction()) {
$state->setValue(
sprintf(
'Transaction with id %d transaction success',
$connection->getLastTransactionId()
)
);
return true;
}
$state->setValue('Rolling back transaction');
$connection->rollBackTransaction();
$state->setValue('Rollback executed');
}
}