PHP code example of debuss-a / problem-details

1. Go to this page and download the library: Download debuss-a/problem-details 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/ */

    

debuss-a / problem-details example snippets


use ProblemDetails\ProblemDetails;

$problem = new ProblemDetails(
    type: 'https://example.com/probs/out-of-credit',
    title: 'You do not have enough credit.',
    status: 403,
    detail: 'Your current balance is 30, but that costs 50.',
    instance: '/account/12345/msgs/abc',
    extensions: [
        'balance' => 30,
        'accounts' => ['/account/12345', '/account/67890']
    ]
);

// JSON serialization
$json = json_encode($problem);

use ProblemDetails\ProblemDetailsException;

try {
    // Your application logic
    if ($user->balance < $item->price) {
        $problem = new ProblemDetails(
            type: 'https://example.com/probs/out-of-credit',
            title: 'You do not have enough credit.',
            status: 403,
            detail: "Your current balance is {$user->balance}, but that costs {$item->price}."
        );
        
        throw new ProblemDetailsException($problem);
    }
} catch (ProblemDetailsException $e) {
    // Deal with the exception, or...
    // ...if set, the middleware will handle this automatically
    throw $e;
}

use Laminas\Diactoros\ResponseFactory;
use ProblemDetails\ProblemDetailsMiddleware;

// For PSR-15 compatible frameworks
$response_factory = new ResponseFactory();
$app->add(new ProblemDetailsMiddleware($response_factory));