PHP code example of gnugat / marshaller

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

    

gnugat / marshaller example snippets




class Article
{
    public function __construct($title, $content)
    {
        $this->title = $title;
        $this->content = $content;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getContent()
    {
        return $this->content;
    }
}

$article = new Article('Nobody expects...', '... The Spanish Inquisition!');

// ...

array(
    'title' => 'Nobody expects...',
    'content' => '... The Spanish Inquisition!',
);

// ...

ugat\Marshaller\MarshallerStrategy;

class ArticleMarshaller implements MarshallerStrategy
{
    public function supports($toMarshal, $category = null)
    {
        return $toMarshal instanceof Article;
    }

    public function marshal($toMarshal)
    {
        return array(
            'title' => $toMarshal->getTitle(),
            'content' => $toMarshal->getContent(),
        );
    }
}

// ...

use Gnugat\Marshaller\Marshaller;

$marshaller = new Marshaller();
$marshaller->add(new ArticleMarshaller());

// ...

$marshalledArticle = $marshaller->marshal($article);

// ...

array('title' => 'Nobody expects...');

// ...

class PartialArticleMarshaller implements MarshallStrategy
{
    public function supports($toMarshal, $category = null)
    {
        return $toMarshal instanceof Article && 'partial' === $category;
    }

    public function marshal($toMarshal)
    {
        return array(
            'title' => $toMarshal->getTitle(),
        );
    }
}

// ...

$marshaller->add(new PartialArticleMarshaller, 1);

$marshaller->marshal($article, 'partial');

// ...

$articles = array($article);
foreach ($articles as $article) {
    $marshaller->marshal($article);
}

// ...

$marshaller->marshalCollection($articles);