PHP code example of tonicforhealth / model-transformer

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

    

tonicforhealth / model-transformer example snippets


 

class Product 
{
    /**
     * @var string
     */ 
    private $name; 
    
    /**
     * @var Category
     */
    private $category;
    
    // ... 
    
    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
    
    /**
     * @return Category
     */
    public function getCategory()
    {
        return $this->category;
    }
}

class Category 
{
    /**
     * @var string
     */ 
    private $name; 
    
    // ... 
    
    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

 

class ProductPresentation
{
    /**
     * @var string
     */ 
    private $name;
     
    /**
     * @var string
     */
    private $categoryName;
    
    /**
     * @var int
     */
    private $purchasedCount;
    
    // ... 
    
    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
    
    /**
     * @return string
     */
    public function getCategoryName()
    {
        return $this->categoryName;
    }
    
    /**
     * @return string
     */
    public function getPurchasedCount()
    {
        return $this->purchased;
    }    
}



class ProductToProductRepresentationModelTransformer implements ModelTransformerInterface
{
	/**
	 * @var ProductRepository
	 */
	private $productRepository;

	// ...

    /**
     * {@inheritdoc}
     */
    public function supports($object, $targetClass)
    {
        return ($object instanceof Product) && is_a($targetClass, ProductRepresentation::class, true);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($object, $targetClass)
    {
    	/** @var Product $product */
    	$product = $object;

    	$purchasedCount = $this->productRepository->computePurchasedCount($product);

    	return new ProductRepresentation(
    		$product->getName(),
    		$product->getCategory()->getName(), 
    		$purchasedCount
    	);
    }
}



$priority = 0;
$modelTransformer->addTransformer($productToProductRepresentationModelTransformer, $priority = 0);



$productRepresentation = $modelTransformer->transform($product, ProductRepresentation::class);