Yii2 component: yii2-gon. Push variables from PHP to JS. > stdout.in Ievgen Kuzminov IT blog

Yii2 component: yii2-gon. Push variables from PHP to JS.

Dec 6, 2015, 3:31:36 PM

This component publishes json serialisable data as 'key -> value' from PHP code into global JS variable window.gon.

Why?

The need for such an extensions came while working on web apps with mixed approach: rich JavaScript GUI on web page, but each page is reloaded and most of bussiness logic is still on the backend side.

The simples solution for a quick prototyping is pushing a data from PHP controller to global JS variable. That makes you free from a lot of REST API getters (you can make a lot without an API at all). So I did the first protype of this extension during "EU Web Challenge 2015" tasks coding. And now publish it as a standalone package.

Idea is inspired by Ruby gem gon https://github.com/gazay/gon (the name is taken from it too. "GON" authors - in case of any naming issues, just ping me :))

Install

Via Composer

$ composer require ijackua/yii2-gon

Configure

Add component to application config `php 'components' => array(

'gon' => 'ijackua\gon\GonComponent'

), And to app `bootstrap` sectionphp $config = array(

'bootstrap' => array('gon'),
...


Full component configuration example
```php
'components' => array(
       'gon' => array(
            'class' => 'ijackua\gon\GonComponent',
            'jsVariableName' => 'gon',
            'globalData' => ['g1' => 1, 'g2' => '2'],
            'showEmptyVar' => true,
        )
),

Usage

Anywhere in your app push key -> value

\Yii::$app->gon->push('someObj', ['a'=>'b']);
\Yii::$app->gon->push('str', 'hello');

On JS side you will get `js > window.gon >> Object

  someObj: Object
     {
       a: "b"
     }
  str: "hello"


## TODO

* Make optional non-global usage. AMD, CommonJS modules.

comments powered by Disqus
Ievgen
Kuzminov "iJackUA"
Web Team Lead
at MobiDev (Kharkiv, Ukraine)
Code in Ruby and Elixir, but still love PHP. Explore ES6 and Vue.js. Explore databases, use Ubuntu and MacOS, think about IT people and management

Notes


Linkify - jQuery plugin for finding URLs in plain-text and converting them to HTML links. It works with all valid URLs and email addresses



Remodal - flat, responsive, lightweight, fast, easy customizable modal window jquery plugin with declarative state notation and hash tracking



Giving a try to Ubuntu 14.04 - so far it's ok. More stable and refined. But it seem to have problems with Cinnamon 2 installation. Oh fine... will wait for Linux MInt 17 to use on my Work machine



Updated blog. Mostly "under-the-hood" changes according to latest Yii2 state, some CSS and server optimisations. In case of any issues please feel free to comment here