PHP code example of crell / transformer

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

    

crell / transformer example snippets


// A product from our domain.
class Product {}

// A Customer from our domain.
class Customer {}

// An HttpResponse object from our framework.
class Response {}

// Contains an HTML string and metadata.
class HtmlBody {} 

// Contains an HTML string and metadata.
class HtmlPage {} 

// Create a new tranformer bus, which will process until it finds a Response.
$bus = new TransformerBus(Response::class);

// Register a transformer for Product objects.
$bus->setTransformer(Product::class, function(Product $p) {
  $fragment = new HtmlBody();
  // Do some business logic here.
  return $fragment;
});

// Register a transformer for Customer objects. Note that it's totally OK
// for multiple objects to get transformed to the same type.
$bus->setTransformer(Customer::class, function(Customer $p) {
  $fragment = new HtmlBody();
  // Do some business logic here.
  return $fragment;
});

// Register a transformer for HtmlBody objects, this one as a function.
function makePage(HtmlBody $p) {
  $page = new HtmlPage();
  // Do some business logic here.
  return $page;
}
$bus->setTransformer(HtmlBody::class, 'makePage');

// Register a transformer for HtmlPage objects. Any PHP callable works.
class PageTransformer {
  public function transform(HtmlPage $h) {
    $response = new Response();
    // Do some business logic here.
    return $response;
  }
}
$t = new PageTransformer();
$bus->setTransformer(HtmlBody::class, [$t, 'transform']);

$p = getProductFromSomewhere();
$response = $bus->transform($p);

$c = getCustomerFromSomewhere();
$response = $bus->transform($c);

$h = getHtmlBodyFromSomewhere();
$response = $bus->transform($h);

$h = getHtmlPageFromSomewhere();
$response = $bus->transform($h);

// This is effectively a no-op.
$r = getResponseFromSomewhere();
$response = $bus->transform($r);

$bus->setAutomaticTransformer(function(Product $p) {
  $fragment = new HtmlBody();
  // Do some business logic here.
  return $fragment.
});