PHP code example of netzmacht / php-javascript-builder

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

    

netzmacht / php-javascript-builder example snippets



$ php composer.phar 



 Foo implements ConvertsToJavascript
{
    private $bar;

    public function __construct($bar)
    {
        $this->bar = $bar;
    }

    public function encode(Encoder $encoder, $flags = null)
    {
        return 'console.log(' . $encoder->encodeReference($this->bar) . ')' . $encoder->close($flags);
    }
}

class Bar implements ConvertsToJavascript, ReferencedByIdentifier
{
    public function encode(Encoder $encoder, $flags = null)
    {
        return sprintf (
            '%s = new Bar()%s',
            $encoder->encodeReference($this),
            $encoder->close($flags)
        );
    }

    public function getReferenceIdentifier()
    {
        return 'bar';
    }
}

$builder = new Builder();

$bar = new Bar();
$foo = new Foo($bar);

echo '<pre>';
echo $builder->encode($foo);
// bar = new Bar();
// console.log(bar);


$ php composer.phar 


// Setup the dispatcher outside so that the listeners can be added.
$dispatcher = new EventDispatcher();
$factory    = function(Output $output) use ($dispatcher) {
    $encoder = new ChainEncoder();
    
    $encoder
        ->register(new ResultCacheEncoder())
        ->register(new \EventDispatchingEncoder())
        ->register(new JavascriptEncoder($output));
    
    return $encoder;
};