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

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

    

czepter / cakephp-fractal-transformer-view example snippets


namespace App\Controller;

class ArticlesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        
        $this->loadComponent('RequestHandler');
        
        $this->viewBuilder()->setClassName('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->viewBuilder()->setOption('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->viewBuilder()->setOption('transform', ['articles' => '\App\Model\Transformer\CustomArticleTransformer']);

$this->viewBuilder()->setOption('transform', ['articles' => false]);

$this->viewBuilder()->setOption('serializer', new CustomSerializer());