Laravel usage

In order to use JsonMapper with your Laravel application you only need JsonMapper’s LaravelPackage.

Installation

The installation of JsonMapper Laravel package can easily be done with Composer

$ composer require json-mapper/laravel-package

This package makes use of Laravels package auto-discovery mechanism.

* The example shown above assumes that composer is on your $PATH.

Configuration

Copy the package config to your local config with the publish command:

php artisan vendor:publish --provider="JsonMapper\LaravelPackage\ServiceProvider"

The package config enables you to choose between the default JsonMapper or the best-fit JsonMapper. You can check the Setup page for more info of the different types.

Example

<?php

namespace App\Service;

use JsonMapper\LaravelPackage\JsonMapperInterface;

class ApiClient
{
    private JsonMapperInterface $mapper;
    
    public function __construct(private JsonMapperInterface $mapper) {}
    
    public function fetchJokes(): Collection
    {
        $data = file_get_contents('https://official-joke-api.appspot.com/jokes/ten');
        
        return $this->mapper->mapToCollectionFromString($data, new Joke());
    }
}

class Joke
{
    public int $id;
    public string $type;
    public string $setup;
    public string $punchline;
}