PHP code example of xenolope / cartographer

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

    

xenolope / cartographer example snippets


class Contact
{

    /**
     * @var string
     */
    private $name;

    /**
     * @var Address
     */
    private $address;

    /**
     * Note, this property doesn't have a @var docblock, but the corresponding setter
     * below *does* have a type hint
     */
    private $secondaryAddress;

    /**
     * @var Note[]
     */
    private $notes;

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @param Address $address
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }

    /**
     * @param Address $secondaryAddress
     */
    public function setAddress(Address $secondaryAddress)
    {
        $this->secondaryAddress = $secondaryAddress;
    }

    /**
     * @param Note[] $notes
     */
    public function setNotes($notes)
    {
        $this->notes = $notes;
    }
}

// Create a new instance of the Mapper
$mapper = new \Xenolope\Cartographer\Mapper();

// Map a JSON string to a POPO

// PHP 5.4
$object = $mapper->mapString(
    '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}',
    'Vendor\Package\Entity\Contact'
);

// PHP >=5.5
$object = $mapper->mapString(
    '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}',
    Contact::class
);

// Map an already decoded (to array) JSON document to a POPO

// This might happen automatically in your Request class, for example
$jsonDocument = json_decode(
    '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}',
    true
);

// PHP 5.4
$object = $mapper->map($jsonDocument, 'Vendor\Package\Entity\Contact');

// PHP >= 5.5
$object = $mapper->map(
    '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}',
    Contact::class
);