Вывод из PHP в Firebug. Helper для CakePHP

Как вы делаете отладку? В запутанных случаях я использую Zend Debugger, а в простых случаях пишу pr($variable).

Прочитав Ярослава, я вдруг осознал насколько удобно было бы не мусорить окно браузера, а красиво выводить отладочные сообщения в Firebug. Особенно приятно туда выводить сложные объекты и большие массивы так как Firebug позволяет удобно такие вещи просматривать.

Но реализация от Ярослава мне не подходит.
Там много всяких полезностей, но мне они не нужны :). Схожие функции выполняет будет когда-то выполнять дополнительная панель к Firebug - FirePHP. Но это совсем уже монстр, к тому же пока очень бета. Может, когда его доработают, то я себе установлю.

А пока мне просто нужно писать во View

PHP:
  1. <?=$jsDebug->console($strangeVariable)?>

, где переменная может быть как целым числом, так и сложным массивом или объектом. Это перекрывает 90% потребностей. Бонусом является возможность добавления стандартных иконок Firebug (warn, info, error) и иногда устанавливать переменную javascipt, чтобы потом javascriptом её и обрабатывать. А для тех, у кого нет Firebug, можно использовать метод alert.

Как обычно начинаем с теста, который покажет как использовать этот helper

PHP:
  1. <?
  2.  
  3. loadHelper('JsDebug');
  4.  
  5. class JsDebugTest extends UnitTestCase {
  6.     var $helper = null;
  7.  
  8.     function setUp() {
  9.         $this->helper = new JsDebugHelper();
  10.     }
  11.  
  12.     function testConsole() {
  13.         $result = $this->helper->console('');
  14.         $this->assertEqual('<script type="text/javascript">console.log(eval(""))</script>', $result);
  15.  
  16.         $result = $this->helper->console('1');
  17.         $this->assertEqual('<script type="text/javascript">console.log(eval("1"))</script>', $result);
  18.  
  19.         $result = $this->helper->console(array(1,2,3));
  20.         $this->assertEqual('<script type="text/javascript">console.log(eval([1,2,3]))</script>', $result);
  21.  
  22.         $result = $this->helper->console(array('one'=>'test','two'=>array(1,2,3),3));
  23.         $this->assertEqual('<script type="text/javascript">console.log(eval({"one":"test","two":[1,2,3],"0":3}))</script>', $result);
  24.     }
  25.  
  26.     function testConsoleTypes() {
  27.         $result = $this->helper->console('1', 'info');
  28.         $this->assertEqual('<script type="text/javascript">console.info(eval("1"))</script>', $result);
  29.  
  30.         $result = $this->helper->info('1');
  31.         $this->assertEqual('<script type="text/javascript">console.info(eval("1"))</script>', $result);
  32.  
  33.         $result = $this->helper->warn('1');
  34.         $this->assertEqual('<script type="text/javascript">console.warn(eval("1"))</script>', $result);
  35.  
  36.         $result = $this->helper->error('1');
  37.         $this->assertEqual('<script type="text/javascript">console.error(eval("1"))</script>', $result);
  38.     }
  39.  
  40.     function testSet() {
  41.         $result = $this->helper->set('', 'test');
  42.         $this->assertEqual('<script type="text/javascript">var test = eval("")</script>', $result);
  43.  
  44.         $result = $this->helper->set('1', 'test');
  45.         $this->assertEqual('<script type="text/javascript">var test = eval("1")</script>', $result);
  46.  
  47.         $result = $this->helper->set(array(1,2,3), 'test');
  48.         $this->assertEqual('<script type="text/javascript">var test = eval([1,2,3])</script>', $result);
  49.  
  50.         $result = $this->helper->set(array('one'=>'test','two'=>array(1,2,3),3), 'test');
  51.         $this->assertEqual('<script type="text/javascript">var test = eval({"one":"test","two":[1,2,3],"0":3})</script>', $result);
  52.     }
  53.  
  54.     function testAlert() {
  55.         $result = $this->helper->alert('');
  56.         $this->assertEqual('<script type="text/javascript">alert(\'\')</script>', $result);
  57.  
  58.         $result = $this->helper->alert('1');
  59.         $this->assertEqual('<script type="text/javascript">alert(\'1\')</script>', $result);
  60.  
  61.         $result = $this->helper->alert(array(1,2,3));
  62.         $this->assertEqual('<script type="text/javascript">alert(\'Array\n(\n    [0] => 1\n    [1] => 2\n    [2] => 3\n)\n\')</script>', $result);
  63.  
  64.         $result = $this->helper->alert(array('one'=>'test','two'=>array(1,2,3),3));
  65.         $this->assertEqual('<script type="text/javascript">alert(\'Array\n(\n    [one] => test\n    [two] => Array\n        (\n            [0] => 1\n            [1] => 2\n            [2] => 3\n        )\n\n    [0] => 3\n)\n\')</script>', $result);
  66.     }
  67.  
  68.     function tearDown() {
  69.         unset($this->helper);
  70.     }
  71. }
  72.  
  73.  
  74. ?>

А вот и сам helper

PHP:
  1. <?
  2.  
  3. /**
  4. * JsDebug helper
  5. *
  6. * Sends php variables to Firebugs console.log or just sets javascript variable
  7. * Console method requires Firebug at client browser. You can download it at http://www.getfirebug.com
  8. *
  9. * @author Vladimir Luchaninov
  10. * @version 1.0 (16 Oct 2007)
  11. */
  12.  
  13. class JsDebugHelper extends Helper {
  14.  
  15.     var $varPrefix = 'JsDebug_';
  16.     var $varCounter = 1;
  17.  
  18.     /**
  19.      * Makes Firebug console.log of $value
  20.      *
  21.      * @param variant $value
  22.      * @param string $type
  23.      *     You may specify icon near the debug message. Possible values: info, warn, error
  24.      * @return string
  25.      */
  26.     function console($value, $type=null) {
  27.         if (empty($type) || !in_array($type, array('info', 'warn', 'error'))) {
  28.             $type = 'log';
  29.         }
  30.  
  31.         return $this->output($this->_wrapScript('console.'.$type.'('.$this->_wrapEval($value).')'));
  32.     }
  33.  
  34.     function info($value) {
  35.         return $this->console($value, 'info');
  36.     }
  37.  
  38.     function warn($value) {
  39.         return $this->console($value, 'warn');
  40.     }
  41.  
  42.     function error($value) {
  43.         return $this->console($value, 'error');
  44.     }
  45.  
  46.     /**
  47.      * Alerts variable dump
  48.      *
  49.      * @param variant $value
  50.      * @return string
  51.      */
  52.     function alert($value) {
  53.         ob_start();
  54.         print_r($value);
  55.         $value = ob_get_clean();
  56.  
  57.         return $this->output($this->_wrapScript('alert(\''.$this->_escapeString($value).'\')'));
  58.     }
  59.  
  60.     /**
  61.      * Sets javascript variable
  62.      *
  63.      * @param variant $value
  64.      * @param string $name
  65.      *     If empty then name will be generated as JsDebug_1, JsDebug_2, ...
  66.      * @return string
  67.      */
  68.     function set($value, $name=null) {
  69.         if (empty($name)) {
  70.             $name = $this->varPrefix . $this->varCounter++;
  71.         }
  72.  
  73.         return $this->output($this->_wrapScript('var '.$name.' = '.$this->_wrapEval($value)));
  74.     }
  75.  
  76.     /**
  77.      * Very similar to Javascript Helper escapeString
  78.      * But this version also includes replacement of </script>
  79.      *
  80.      * @param string $string
  81.      * @return string
  82.      */
  83.     function _escapeString($string) {
  84.         $escape = array(
  85.             "\r\n" => '\n',
  86.             "\r" => '\n',
  87.             "\n" => '\n',
  88.             '"' => '\"',
  89.             "'" => "\\'",
  90.             '</script>' => '<\/script>'
  91.         );
  92.         return r(array_keys($escape), array_values($escape), $string);
  93.     }
  94.  
  95.     function _wrapScript($s) {
  96.         return '<script type="text/javascript">'.$s.'</script>';
  97.     }
  98.  
  99.     function _wrapEval($value) {
  100.         return 'eval('.json_encode($value).')';
  101.     }
  102.  
  103. }
  104.  
  105. ?>


Понравилось?

  1. Подпишись через RSS
  2. Расскажи о http://php.southpark.com.ua друзьям.
    Все способы хороши: ICQ, E-mail, свой блог, комментарий в чужом блоге или сообщение на форуме
  3. Добавь статью на news2.ru, Хабрахабр или в закладки

Огромное спасибо!

И не стесняйтесь комментировать - у меня стоит плагин, который убирает rel="nofollow" у людей, которые написали больше 5 комментариев.

RSS feed | Trackback URI

11 комментариев »

Comment by Mick
2007-10-20 15:27:30

, CakePHP? Zend Debugger ?

 
Comment by
2007-10-20 17:48:38

Zend Platform (-, ZendCore), Zend Studio. breakpoints.
( IE Firefox).
Zend profiler.

Zend, XDebug + Eclipse/Komodo.

 
Comment by sp3ctr00m
2007-10-22 16:25:15
 
Comment by
2007-10-22 20:38:44

@sp3ct00m: , . , Javascript, . .

, , CakePHP. "" :)

, ( , 8- ).

 
Comment by VolCh
2007-10-24 10:48:59

, CakePHP :)
Firebug,

, sp2ctr00m , :( - , , http://ifolder.ru/ ? :)

 
Comment by VolCh
2007-10-24 10:50:28

.. , -61 , 580(i8080) :)

 
Comment by
2007-10-24 21:01:04

@VolCh: -61 , : 101 - . 580 , - :)

. , , helper Firebug Cake.

 
Comment by VolCh
2007-10-24 23:09:44

:)

 
Comment by Лобач Олег Subscribed to comments via email
2007-12-07 10:04:46

Собрат по Спекки! Уважаю! :)

Я в начале 90-х несколько лет посвятил ассемблеру Z-80... Вот было время! :)

 
Comment by обычный пользователь
2008-01-15 05:04:23

Распишите пожалуйста подробней процесс установки.
я назвал первый файл test.php.
Положил в папку www вместе с JsDebugHelper.php
запустил http://anyname/test.php

firefox (с firebug) выдал ошибку
Call to undefined function loadHelper() ... on line 3

Еще опишите конечный результат. Как я понял, будет записываться console.log.

 
2008-01-25 22:03:28

[...] Вывод сообщений в FireBug из cakePHP (Tested on 1.2.x) [...]

 
Имя (required)
E-mail (required - never shown publicly)
URL
Текст комментария
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.