Symfony VarDumper - without Symfony

Working on Drupal 8, which has the Symfony stack, I’ve fell in love with the var-dumper class first introduced to me in this article from a few weeks back. Today I decided to whip up a tiny script that loads it regardless of the framework in place - making it accessible at all times.

The script is so small that, well, here it is.

<?php
/*
 * VarDumper Anywhere, a small prepend script.
 * To use point to this file from PHP's auto_prepend_file
 * directive
 *
 * http://php.net/manual/en/ini.core.php#ini.auto-prepend-file
 *
 * We'll start by wrapping ourselves in a closure so
 * that we leave behind no variables.
 */
call_user_func(function(){
  /*
   * We will need an autoloader.  This isn't PSR-4 compliant, 
   * but it is sufficient to find all the files in the var-dumper
   * package as it stands today.  We make it a closure and
   * assign that closure to a variable so we can unregister it
   * when we're done.
   */
  $autoload = function($class) {

    $stack = explode("\\", $class);
    $class = array_pop($stack);
    $namespace = array_pop($stack);
    require_once(__DIR__.'/Symfony/Component/VarDumper/'.$namespace.'/'.$class.'.php');
    return true;
  };

  /*
   * Register it.
   */
  spl_autoload_register($autoload);

  /*
   * Traverse and touch every file in the VarDumper project, insuring
   * that all its code is loaded.
   */
  foreach(glob(__DIR__.'/Symfony/Component/VarDumper/*', GLOB_ONLYDIR) as $dir) {
    if ($dir === __DIR__.'/Symfony/Component/VarDumper/Tests') continue;

    foreach(glob($dir.'/*.php') as $file ) {
      require_once($file);
    }
  }
  /*
   * And now the core file of the package
   */
  require_once(__DIR__.'/Symfony/Component/VarDumper/VarDumper.php');
  /*
   * We're done. Unregister the autoloader.
   */
  spl_autoload_unregister($autoload);
});

I put this file as prepend.php in the root of the VarDumper project, then placed a copy off by itself in my /usr/local directory. As mentioned in my comments, it’s written in such a way that no variables are left behind nor is its autoloader left behind so as to insure that any code you’re about to run won’t be disturbed by its presence. I’ve tested this with Drupal 7 and Wordpress 3.9 with no conflicts.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.