PHP code example of olivermack / duzzle

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

    

olivermack / duzzle example snippets


$duzzle = DuzzleBuilder::create([
    // place your guzzle default options here
    'base_uri' => 'https://jsonplaceholder.typicode.com/',
])
    ->withDefaultSerializer()
    ->build();

// without any further specification/configuration the client
// will automatically deserialize the resulting data as php array
$result = $duzzle->request('GET', '/todos/1')->getDuzzleResult();

/**
 * array(4) {
 *   'userId' => int(1)
 *   'id' => int(1)
 *   'title' => string(18) "delectus aut autem"
 *   'completed' => bool(false)
 * }
 */

class Todo
{
    public ?int $id = null;
    public int $userId;
    public string $title;
    public bool $completed;
}

$result = $duzzle->request('GET', '/todos/1', [
    DuzzleOptionsKeys::OUTPUT => Todo::class
    // or
    'output' => Todo::class,
])->getDuzzleResult();

/**
 * class Todo#159 (4) {
 *   public ?int $id => int(1)
 *   public int $userId => int(1)
 *   public string $title => string(18) "delectus aut autem"
 *   public bool $completed => bool(false)
 * }
 */

$newTodo = new Todo();
$newTodo->userId = 1;
$newTodo->completed = true;
$newTodo->title = 'My new task!';

$createdTodoResult = $duzzle->request('POST', '/todos', [
    DuzzleOptionsKeys::INPUT => $newTodo,
    // if we don't provide an output DTO we'll get the result as array!
    DuzzleOptionsKeys::OUTPUT => Todo::class,
]);

// define your serializer
$serializer = new \Symfony\Component\Serializer\Serializer();
// pass it to the builder
$duzzle = DuzzleBuilder::create($options)
    ->withSerializer($serializer)
    ->build();

$duzzle = DuzzleBuilder::create([
    DuzzleOptionsKeys::INPUT_VALIDATION => DefaultStrategyKey::BLOCKING->value,
    // same as:
    'input_validation' => 'blocking',
    
    DuzzleOptionsKeys::OUTPUT_VALIDATION => DefaultStrategyKey::BLOCKING->value,
    // same as:
    'output_validation' => 'blocking',
    
    // ...other options
])
    ->withDefaultSerializer()
    ->withDefaultValidator()
    ->build();

use Symfony\Component\Validator\Constraints as Assert;

class Todo
{
    public ?int $id = null;
    #[Assert\Positive]
    public int $userId;
    #[Assert\NotBlank]
    #[Assert\Length(min: 1, max: 255)]
    public string $title;
    public bool $completed;
}

$todo = new Todo();
$duzzle->request('POST', '/todos', [
    'input' => $todo,
    'input_validation' => 'blocking',
])->getDuzzleResult();