We're growing into something new. Read More
BaylorRae

Baylor Rae'


Discussion

Stack Exchange - Typography

A few months ago someone suggested that a site be added to the Stack Exchange network for typography. It seems that I wasn't the only one interested because, to my delight, I received an email this morning letting me know that it was going into the commitment phase. I'm assuming that users here are interested in learning more about typography, and since the site needs beta users, ya'll might be willing to sign up.

<?php

class Benchmark {
  
  /**
   * Creates a loop that lasts for $allowed_time and logs how many
   * times a function was able to run
   *
   * @param string $name the name of the test 
   * @param function $test the function to run
   * @param integer $allowed_time seconds to run a function
   * @return string
   * @author Baylor Rae'
   */
  public static function run_test($name, $test, $allowed_time = 10) {
    
    // get the time the function was called
    $start_time = microtime(true);
    
    // stores how many times $test was able to run
    $times_run = 0;
    
    // don't allow output
    ob_start();
    
    // run the $test function until time is up
    do {
      call_user_func($test);
      $times_run++;
    }while( number_format(microtime(true) - $start_time, 0) < $allowed_time);
    
    // end output buffering
    ob_end_clean();
    
    // return the formatted results
    return self::results($name, $times_run, $allowed_time);
  }
  
  /**
   * Formats results for easy reading
   *
   * @param string $name name of the test
   * @param integer $times_run number of times the test ran
   * @param integer $allowed_time how long the test was allowed to run
   * @return string
   * @author Baylor Rae'
   */
  private static function results($name, $times_run, $allowed_time) {
    $output = '<h2>Results for ' . $name . '</h2>';
    $output .= '<dl>';
      
      $output .= '<dt>Times Run</dt>';
      $output .= '<dd>' . number_format($times_run, 0) . '</dd>';
      
      $output .= '<dt>Ran For</dt>';
      $output .= '<dd>' . $allowed_time . 's</dd>';
      
    $output .= '</dl>';
    return $output;
  }
  
}

PHP Benchmark Class

I recently learned about jsperf.com and I've really enjoyed looking at the speed results of different pieces of code. However, I couldn't find any sites that did the same for PHP and I've really wanted to test different ideas that I've had. I wrote the above code, but I'm not completely confident it does the job as efficiently as possible. I'm hoping that ya'll don't mind looking over the actual loop to see if there's a better way to force the script to run for a specified amount of time. Writing a Test <?php require 'Benchmark.php'; $results = array(); // my version of un-camel casing a word function test_1() { return strtolower(implode(' ', preg_split('/(?<=\\w)([A-Z])/', 'aCamelCasedWord'))); } // CakePHP's version of un-camel casing a word function test_2() { return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', 'aCamelCasedWord')); } $results[] = Benchmark::run_test('My Version', 'test_1', 10); $results[] = Benchmark::run_test('Cake\'s Version', 'test_2', 10); foreach( $results as $result ) echo $result; ?> Raw

ul { margin-left: 1em; list-style: disc; }
ul li {
    text-indent: -1em;
    width: 100px;
    padding-left: 1em;
}

Negative Text Indent in CSS

As you probably know text-indent can be used to simulate adding five spaces in a paragraph. Which can mimic paragraph styles in books. But I just learned that negative text-indent will indent all but the first line in an element, making paragraphed lists much easier to read. [Demo on jsFiddle]

<?php

require 'console.class.php';

Console::log('This is pretty cool, eh?');

$user = array(
  'username' => 'BaylorRae',
  'email' => '[email protected]',
  'posts' => array(
    array('title' => 'Whoa! This is sweet!', 'body' => 'blah blah blah ...'),
    array('title' => 'Did you see what I made?', 'body' => 'blah blah blah ...')
    )
  );
  
Console::log($user);

PHP Console

This is a small script that I wrote to make PHP debugging a little easier. I made it because my app was dealing with a lot of redirects, and I wanted to log information without it being erased after the redirect. Everything is stored in a text file that gets created in the same directory as console.php. You can run it with ./console.php I made a video explaining how it works. And you can get the code on GitHub. This isn't a revolutionary approach that will make debugging easier in every situation. But it works perfectly for me and my application :) - Also, this was my first attempt at creating a script that runs in Terminal so there may be a few problems with it.

<?php

class FlashMessages {
  private $messages = array();
  private $now = false;
  
  private function __construct() {
    // Save all messages
    $this->messages = $_SESSION['flash_messages'];
    
    // Reset all flash messages or create the session
    $_SESSION['flash_messages'] = array();
  }
  
  // Only allows one instance of the class
  public static function instance() {
    static $instance = null;
    if( $instance === null )
      $instance = new FlashMessages;

    return $instance;
  }
  
  // Allows simple message adding
  // usage: flash()->notice('You have logged in successfully');
  public function __call($name, $args) {
    $message = $args[0];
    $this->message($name, $message);
  }
  
  public function message($name, $message) {
    if( $this->now ) {
      $this->messages[] = array(
        'name' => $name,
        'message' => $message
      );
      $this->now = false;
    }else
      $_SESSION['flash_messages'][] = array(
        'name' => $name,
        'message' => $message
      );
  }
  
  public function each($callback = null) {
    
    // Set default markup
    if( $callback === null ) {
      $callback = function($name, $message) {
        echo '<div id="flash_' . $name . '">' . $message . '</div>';
      };
    }
    
    foreach( $this->messages as $flash ) {
      echo $callback($flash['name'], $flash['message']);
    }
  }
  
  // Allows message to be displayed instantly
  // (opposed to waiting for next page request)
  public function now() {
    $this->now = true;
    return $this;
  }
  
}

// Allows shorthand
function flash() {
  return FlashMessages::instance();
}

PHP Flash Messages

This is a class that I wrote today for a small application that I've been working on. I wrote it to replicate flash messages found in Rails and to practice the singleton pattern. /* EXAMPLES */ // These will be loaded on the next page flash()->message('notice', 'You have logged in successfully'); flash()->notice('You have logged in successfully'); // same as code above // This will run on the next flash()->each() call flash()->now()->alert('Something went wrong deleting the record'); Raw Code » I put it on GitHub so you can fork it and make it better. Please let me know where I can improve it.

(function($) {
    $.fn.flash_message = function(options) {
      
      options = $.extend({
        text: 'Done',
        time: 1000,
        how: 'before',
        class_name: ''
      }, options);
      
      return $(this).each(function() {
        if( $(this).parent().find('.flash_message').get(0) )
          return;
        
        var message = $('<span />', {
          'class': 'flash_message ' + options.class_name,
          text: options.text
        }).hide().fadeIn('fast');
        
        $(this)[options.how](message);
        
        message.delay(options.time).fadeOut('normal', function() {
          $(this).remove();
        });
        
      });
    };
})(jQuery);

jQuery Flash Messages

Try It Out I wrote this plugin to make it easy to add flash messages for user feedback. I used ajax to add an item to the cart and wanted a simple way to inform the user the action had taken place. This little plugin is easy to use and should be unobtrusive to your markup. Here's an example of usage. $('#status-area').flash_message({ text: 'Added to cart!', // text to show how: 'append', // ['append', 'prepend', 'before', 'after'] time: 1000, // how long should the message be visible class_name: 'success' // additional class names for CSS hooks }); Raw Code » I'm relatively new to jQuery/javascript so please let me know where it can be improved.