Forming A Contract For An HTTP Request - axiom82/PHP-Contract GitHub Wiki
In the context of certifying HTTP requests in PHP applications, using Contracts is a simple, yet powerful solution.
The following method handles an HTTP request for assigning a company manager to a company. The Contract for the request requires that a $companyId and $managerId are present in the request parameters. Following this simple check, the Contract begins to verify the existance of valid $company and $manager rows in the database.
<?php
public function assignCompanyManagerAction(){
try {
$contract = new Contract();
$companyId = $_REQUEST['companyId'];
$managerId = $_REQUEST['managerId'];
$contract->term('companyId', $companyId)->id()-end()
->term('managerId', $managerId)->id()->end()
->metOrThrow();
/* The first call to the database will not happen unless the terms for companyId and managerId are met */
$company = $companyModel->getCompany($companyId);
$contract->term('company', $company)->row()->metOrThrow();
/* The second call to the database will not happen unless the terms for companyId, managerId, and company are met */
$manager = $companyModel->getManager($managerId);
$contract->term('manager', $manager)->row()->metOrThrow();
/* Already, we have spared two database requests. Let's make it three if the information is invalid. This one is the most important, as without PHP-Contract, it could store illogical information */
$companyManagerId = $companyModel->createCompanyManager($companyId, $managerId);
$contract->term('companyManagerId', $companyManagerId)->id()->metOrThrow();
}
catch(Contract_Exception $exception){
echo $exception->term;
}
}
?>If the contract, having all of these terms defined, is met, then the assignment of the manager to the company is tried. If any of these terms do not meet their definitions, a Contract Exception is thrown, and the unmet term is made available in Contract_Exception::term. In the catch block, with the term available from within the thrown exception, you can do just about any type of error logging or user interface messaging as needed. If you intend to perform separate actions for each term thrown, using a switch in the catch block would be an excellent routing solution.
For more information on PHP-Contract and clear usage examples, see our Wiki front page.