PHP MVC: where to place dynamically generated Javascript

Most PHP MVC systems follow a pattern where a request is routed to a specific controller action, and then the controller sets up a bunch of variables to use in the view.

When you work in an agency / service workspace that uses a lot of dynamic HTML for user interface elements, these templates lead to a lot of javascript with variables of the form

<script type="text/javascript">
    jQuery(document).ready(function(){
        $('#ui-element).init(
            {
                'param1':<?=$this->param1;?>,
                'param2':<?=$this->param2;?>,                   
            }
        );
    });
</script>

While this works, I found that this leads to views with a terrible combination of HTML, PHP and Javascript spaghetti. It also offends a certain class of interface developers, which believes that all javascript should be included in external files.

, / ? , Javascript PHP MVC, , ? , , ** , .

+3
2

: , , php-/, ob_start/ob_get_clean, js -, js . php...

, - :

class UnobtrusiveJsHelper {
  protected static $_instance;
  protected $_js = array();
  protected $_ready = array();

  public static function getInstance()
  {
  }

  public static function setInstance(UnobtrusiveJsHelper $instance)
  {
  }

  public function captureStart($key = null)
  {
    if(null !== $key)
    {
      $this->_js[$key] = null;
    }
    ob_start();
  }

  public function captureEnd($key = null)
  {
    if(null !== $key)
    {
      $this->_js[$key] = ob_get_clean();
      return;
    }
    $this->_js[] = ob_get_clean();

   public function __toString()
   {
      return $this->dumpJs() . $this->_dumpReady();
   }

   public function dumpJs(array $attributes = null)
   {
      if(!empty($this->_js))
      {
         return "<script type=\"text/javascript\">". implode("\n", $this->_js) . "</script>";
      }

      return null;
   }

   public function dumpReady(array $attributes = null)
   {
      if(!empty($this->_js))
      {
         return '<script type="text/javascript">$(document).ready(function(){'. implode("\n", $this->_js) . '});</script>';
      }

      return null;
   }

}

: $js = UnobtrusiveJsHelper::getInstance();

:

<?php $js->captureStart(); ?>
  var myjsvariable = 0;
<?php $js->captureEnd();

( ): <?php echo isset($js) ? $js : null ?>


, . , Zend_Framework onLoad/Ready . .

, jQ, - Symfony.

, $jq->setVar('myjsvar', 1);, , , - :

var myjsvar = 1; script .

ZendX_Jquery Zend_Dojo .

+3

. , < 100 , , , , . , js , ( ):

<script src='/js/widgets.js'></script>

<script type="text/javascript">
    jQuery(document).ready(function(){
         showSomeWidget(<?=$this->name ?> , <?=$this->place ?> );
    }
</script>

templating jQuery, Dojo, , .

0

Source: https://habr.com/ru/post/1728084/


All Articles