PHP code example of jeffersonsimaogoncalves / cakephp-fractal-transformer-view

1. Go to this page and download the library: Download jeffersonsimaogoncalves/cakephp-fractal-transformer-view 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/ */

    

jeffersonsimaogoncalves / cakephp-fractal-transformer-view example snippets


namespace App\Controller;

class ArticlesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        
        $this->viewBuilder()->className('FractalTransformerView.FractalTransformer');
    }

    public function index()
    {
        // Set the view vars that have to be serialized.
        $this->set('articles', $this->paginate());
        // Specify which view vars JsonView should serialize.
        $this->set('_serialize', ['articles']);
    }
}

namespace App\Model\Transformer;

use App\Model\Entity\Article;
use League\Fractal\TransformerAbstract;

class ArticleTransformer extends TransformerAbstract
{
    /**
     * Creates a response item for each instance
     *
     * @param Article $article post entity
     * @return array transformed post
     */
    public function transform(Article $article)
    {
        return [
            'title' => $article->get('title')
        ];
    }
}

$this->set('_transform', ['articles' => '\App\Model\Transformer\CustomArticleTransformer']);

$this->set('_transform', ['articles' => false]);