Chronicles of a build – qTranslate Headway Theme block 05

Dissatisfied with last post result I’ve retouched the code of the qTranslate Headway Block plugin to move the methods related to Javascript block options handling in their own class.
Previous version did all the script enqueueing in the main Block class burdening it with responsibilities not related to it; the main qtblock\Block class now reads

<?php
namespace qtblock;

class Block extends \HeadwayBlockAPI
{
    public $id = 'qtblock';
    public $name = 'qTranslate language chooser';
    public $options_class = '\qtblock\BlockOptions';
    public $description = 'An Headway block to display qTranslate plugin language chooser on the page.';
    protected $options_handler = null;

    public function init()
    {
        $this->options_handler = new \qtblock\BlockOptionsHandler($this->id);
    }

    public function content($block)
    {
    ...

And it’s storing a reference to an instance of the qtblock\BlockOptionsHandler class

<?php
namespace qtblock;

class BlockOptionsHandler
{
    public function __construct($blockId)
    {
        add_action('headway_block_options_' . $blockId, array($this,'printVisualEditorScripts'));
    }

    public function printVisualEditorScripts()
    {
        // load minified script version by default
        $postfix = '.min';
        if (defined('SCRIPT_DEBUG')) {
            // load non minified scrip
            // t version if script debug is active
            $postfix = '';
        }
        $src = QTBLOCK_BLOCK_URL . "assets/js/qtblock_visual_editor$postfix.js";
        $this->appendScript($src);
    }

    protected function appendScript($src)
    {
        $out = '';
        $out .= '<script type="text/javascript">';
        $out .= 'var script   = document.createElement("script");
        script.type  = "text/javascript";
        script.src  = "' . $src . '"
        document.body.appendChild(script)';
        $out .= '</script>';
        echo $out;
    }
}

Details

The file tree now reads a little clearer and the single responsibility principle is restored

/includes
|   Main.php                // inits constants and requires the plugin files
|   Block.php               // inits and serves the block content
|   BlockOptions.php        // inits the block visual editor options
|   BlockOptionsHandler.php // manages the block options behaviours via js

Code on GitHub

The updated code can be found on GitHub.