Code snippets for symfony 1.x

Navigation

Snippets by user Kris Wallsmith

Make Your Dynamic Page States Bookmarkable

I've found this to be a pretty good solution for the dynamic page state v. bookmarking conflict that prevents users from bookmarking a specific state of your dynamic page. Typically, if a general user bookmarks your page after spending some time interacting with its dynamic features, she will be disappointed to find her bookmark doesn't reflect the state of the page when she bookmarked it.

If your Javascript is built in a way that you can hijack the window's onLoad handler to initialize a custom state, based what fragment might be in the URI, you just might find this helper function useful.

JavascriptHelper.php

Save this to your project or application's /lib/helper folder.

<?php
 
require_once(sfConfig::get('sf_symfony_lib_dir') . '/helper/JavascriptHelper.php');
 
/**
 * An alternative to the sf default link_to_function.
 * 
 * Adds logic to onclick's concat'd "; return false;" so it only shows up if 
 * the value of the href option doesn't include a #fragment. If no fragment is
 * embedded in the href it is set to "javascript:void(0)" a la Google. 
 * 
 * With the "; return false;" absent, the fragment will show up in the 
 * browser's address bar, and will be included if the user copies the link or 
 * bookmarks the current state of your dynamic page. You can then add a bit of 
 * logic to your window initialization Javascript to detect any fragments in 
 * the URL and adjust the onLoad state accordingly.
 * 
 * @author  Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * @version tested on symfony 1.0.3
 * @see     link_to_function()
 * 
 * @param   string $name
 * @param   string $function
 * @param   mixed $options
 * 
 * @return  string
 */
function my_link_to_function($name, $function, $options = array())
{
    $options = _parse_attributes($options);
 
    $has_href = isset($options['href']);
 
    if(!isset($options['href']))
    {
        $options['href'] = 'javascript:void(0)';
    }
    $options['onclick'] = $function;
 
    if(!$has_href || strpos($options['href'], '#') === false)
    {
        $options['onclick'] .= '; return false;';
    }
 
    return content_tag('a', $name, $options);
}
by Kris Wallsmith on 2007-06-08, tagged helper  javascript 
(2 comments)

Google Analytics / Urchin helper functions

These functions should streamline the process of integrating Google Analytics into your site.

The Code

<?php
 
/**
 * A collection of helper functions for attaching analytics tracking code to
 * links. Used for outbound links and downloads. Functions all produce normal
 * links when analytics is turned off in the configuration.
 * 
 * These functions rely on two configuration variables and the layout code,
 * below. The following variables are required in your app.yml file:
 * 
 * <code>
 *   prod:
 *     analytics:
 *       enabled: on
 *       uacct: UA-XXXXXXX-X
 *   stage:
 *     analytics:
 *       enabled: on
 *       uacct: UA-XXXXXXX-Y
 *   all:
 *     analytics:
 *       enabled: off
 * </code>
 * 
 * Add this code to your layout files for any pages you want to track using
 * Urchin. This could also be done using a filter. Notice you can include a
 * parameter in your response object, 'ut_param', that will be passed to the
 * initial urchinTracker call, if it's present.
 * 
 * <code>
 *     <?php if(sfConfig::get('app_analytics_enabled')): ?>
 *     <script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"></script>
 *     <script type="text/javascript">
 *     _uacct = "<?php echo sfConfig::get('app_analytics_uacct') ?>";
 *     urchinTracker(<?php if($ut_param = sfContext::getInstance()->getResponse()->getParameter('ut_param')) echo "\"$ut_param\"" ?>);
 *     </script>
 *     <?php endif; ?>
 * </code>
 * 
 * @package     Urchin Helper Functions
 * @subpackage  helper
 * @author      Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * @version     SVN: $Id$
 * @copyright   Have at it ...
 */
 
use_helper('Url', 'Javascript');
 
/**
 * Build a link that includes a call to the Javascript urchinTracker function.
 * 
 * Usually used when linking off your site or to any file on your site that
 * does not include tracking code (i.e. PDF documents, images, etc.)
 * 
 * @see     sfConfig::get('app_analytics_enabled')
 * 
 * @param   (string) $name - name of the link
 * @param   (string) $internal_uri - module/action or @rule
 * @param   (string) $urchin_uri - custom path for urchinTracker
 * @param   (array)  $options - additional HTML parameters
 * 
 * @return  String
 */
function urchin_link_to($name, $internal_uri, $urchin_uri = null, $options = array())
{
    // Only add onClick handler if analytics is enabled.
    if(sfConfig::get('app_analytics_enabled')) 
    {
        // Determine urchin uri.
        if(!$urchin_uri)
        {
            $urchin_uri = url_for($internal_uri);
        }
 
        // Add onClick.
        $new_onclick = 'urchinTracker(\'' . $urchin_uri . '\');';
 
        $options = _parse_attributes($options);
        $options['onclick'] = isset($options['onclick']) ? 
            ($new_onclick . $options['onclick']) :
            $new_onclick;
    }
 
    return link_to($name, $internal_uri, $options);
}
 
/**
 * Build a link to a Javascript call, including a call to urchinTracker.
 * 
 * @see     sfConfig::get('app_analytics_enabled')
 * 
 * @param   (string) $name - name of the link
 * @param   (string) $function - Javascript code
 * @param   (string) $urchin_uri - custom path for urchinTracker
 * @param   (array)  $options - additional HTML parameters
 * 
 * @return  String
 */
function urchin_link_to_function($name, $function, $urchin_uri, $options = array())
{
    // Create link_to_function.
    $link = link_to_function($name, $function, $options);
 
    // Only add onClick handler if analytics is enabled.
    if(sfConfig::get('app_analytics_enabled')) 
    {
        $link = str_replace('onclick="', 'onclick="urchinTracker(\'' . $urchin_uri . '\');', $link);
    }
 
    return $link;
}
 
?>
by Kris Wallsmith on 2007-05-16, tagged analytics  helper  urchin 

Conditional Plural Helper

This one is so simple I hesitated to post it, but it's also so useful.

PluralHelper.php

<?php
 
/**
 * Returns a smart plural of the supplied word.
 * 
 * If there are more than one items in the supplied array, this function will
 * either add an 's' to the end of the supplied word, or return the optional
 * plural version.
 * 
 * @author  Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * 
 * @param   string $text            The word you want returned
 * @param   array $array            The array of items this word is describing
 * @param   string $plural_version  An optional word to return instead of just 
 *                                  adding an 's' (i.e. "people")
 * 
 * @return  String
 */
function pluralize_if_many($text, $array, $plural_version = null)
{
    return count($array) > 1 ? ($plural_version ? $plural_version : ($text . 's')) : $text;
}
 
?>
by Kris Wallsmith on 2007-05-07, tagged helper  inflector  plural  string 
(2 comments)

Automatic Javascript Include

If you're like me and prefer to code your own Unobtusive Javascript, you'll probably find this snippet handy. It will search through your project's /web/js folder for any .js files that match the current Symfony action.

For example, the snippet/new action would look for /web/js/snippet/snippet.js and /web/js/snippet/new.js, and add them to the response if either exist.

You can also define an optional subfolder within /web/js where you want the filter to look (i.e. "backend").

The Code

<?php
 
/**
 * Looks for Javascript files based on current action/module and adds them to
 * the current response object.
 * 
 * Add this filter to the end of your filter chain in filters.yml, after the 
 * execution filter:
 * 
 * <code>
 *     rendering: ~
 *     web_debug: ~
 *     security:  ~
 *     
 *     # generally, you will want to insert your own filters here
 *     
 *     cache:     ~
 *     common:    ~
 *     flash:     ~
 *     execution: ~
 *     
 *     auto_javascript_include:
 *       class: myAutoJavascriptIncludeFilter
 * </code>
 *
 * @package     Automatic Javascript Include (AJI)
 * @subpackage  filter
 * @author      Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * @version     SVN: $Id$
 * @copyright   Have at it ...
 */
class myAutoJavascriptIncludeFilter extends sfFilter
{
    /**
     * Include external Javascript files based on last action called.
     * 
     * This kicks in on the way back down the filter chain, so we're sure to
     * catch the last action. Looks through the web/js folder for files that
     * match the naming syntax and adds them to the response. 
     * 
     * You can specify a subfolder of the web/js folder for the filter to 
     * search in app.yml.
     * 
     * @author  Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
     * @see     sfConfig::get('app_aji_subfolder')
     * @param   sfFilterChain $filterChain
     */
    public function execute($filterChain)
    {
        $filterChain->execute();
 
        $sf_context  = sfContext::getInstance();
        $sf_response = $sf_context->getResponse();
        $sf_web_dir  = sfConfig::get('sf_web_dir');
 
        $module = $sf_context->getModuleName();
        $action = $sf_context->getActionName();
 
        $sub_folder = sfConfig::get('app_aji_subfolder');
        if($sub_folder && $sub_folder{0} != '/') $sub_folder = '/' . $sub_folder;
 
        $fmt = '/js%s/%s/%s.js';
 
        $mod_mod_js = sprintf($fmt, $sub_folder, $module, $module);
        $mod_act_js = sprintf($fmt, $sub_folder, $module, $action);
 
        if(file_exists($sf_web_dir . $mod_mod_js)) $sf_response->addJavascript($mod_mod_js);
        if(file_exists($sf_web_dir . $mod_act_js)) $sf_response->addJavascript($mod_act_js);
    }
}
 
?>
by Kris Wallsmith on 2007-04-24, tagged filter  javascript 
(6 comments)