yet another lighthouse for Linux geeks and code monkeys
Web Development
Assetic in SmartyBundle
Mar 31st
Being an “unofficial” template engine in Symfony2, Smarty(Bundle) needs to catch up with its Twig and PHP counterparts to provide the same integration and range of features. One of the features missing in SmartyBundle was until recently Assetic.
Assetic
Assetic is an asset management framework for PHP written by Kris Wallsmith. Although this library is available for every PHP project I’m focusing in Symfony2 integration.
For a complete overview of the usage of Assetic in Symfony context please refer to the following cookbook entries:
- Symfony2 – How to Use Assetic for Asset Management
- Symfony2 - How to Minify JavaScripts and Stylesheets with YUI Compressor
Usage in SmartyBundle
SmartyBundle provides the same javascripts, stylesheets and image functions supported in Twig and PHP engines. Usage is quite similar to Twig.
Javascripts
assets='@AcmeFooBundle/Resources/public/js/*'
}
<script type="text/javascript" src="{$asset_url}"</script>
{/javascripts}
Stylesheets
To bring in CSS stylesheets, you can use the same methodologies seen in this entry, except with the stylesheets tag:
assets='@AcmeFooBundle/Resources/public/css/*'
}
<link rel="stylesheet" href="{$asset_url}" />
{/stylesheets}
Combining Assets
You can also combine several files into one. This helps to reduce the number of HTTP requests, which is great for front end performance. It also allows you to maintain the files more easily by splitting them into manageable parts. This can help with re-usability as you can easily split project-specific files from those which can be used in other applications, but still serve them as a single file.
Using the same javascripts example as above. Note the usage of commas to separate assets.
assets='@AcmeFooBundle/Resources/public/js/*,
@AcmeBarBundle/Resources/public/js/form.js,
@AcmeBarBundle/Resources/public/js/calendar.js'
}
<script src="{$asset_url}"></script>
{/javascripts}
In the dev environment, each file is still served individually, so that you can debug problems more easily. However, in the prod environment, this will be rendered as a single script tag.
Block attributes
Here is a list of the possible attributes to define in the block function.
- assets: A comma-separated list of files to include in the build (CSS, JS or image files)
- debug: If set to true, the plugin will not combine your assets to allow easier debug
- filter: A coma-separated list of filters to apply.
- combine: Combine all of your CSS and JS files (overrides `debug`)
- output: Defines the URLs that Assetic produces
- var_name: The variable name that will be used to pass the asset URL to the <link> tag
Full example
And now here goes an example using all available attributes:
assets='@AcmeFooBundle/Resources/public/js/*,
@AcmeBarBundle/Resources/public/js/form.js,
@AcmeBarBundle/Resources/public/js/calendar.js'
filter='yui_js'
output='js/compiled/main.js'
var_name='js_url'
%}
<script src="{$js_url}"></script>
This is work in progress
That’s right, Assetic support in SmartyBundle still requires some real world usage to get rid of its sharp edges and bring it to production level. If you are able to give it a try, test it for a bit and bring your complains over to SmartyBundle issue tracker. I’ll appreciate it!
Introducing SmartyBundle, a Smarty3 bundle for Symfony2
Dec 4th
Hello all! I’ve released yesterday the first version of SmartyBundle on GitHub.
SmartyBundle is Symfony2 a bundle that provides integration for the Smarty3 template engine. It will allow the usage of the Smarty template engine in Symfony2, instead of Twig or PHP templates. SmartyBundle is released under a LPGLv3 license. To download it you may:
Git-clone-it:
$ git clone https://github.com/noiselabs/SmartyBundle.git
or download the repository as a zip file:
https://github.com/noiselabs/SmartyBundle/zipball/master
Full documentation is available on GitHub and after download in the Resources/doc/ folder.
What is Symfony
Symfony is a Open Source PHP Web Development Framework. It is currently my PHP framework of choice that first grabbed my attention by its standalone components and got me back to PHP after digging into the, Python-based, TurboGears Web framework.
What is Smarty
Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. Version 3 brings some important improvements like the addition of template inheritance and a complete code rewrite to make use of new PHP5 capabilities.
Try it!
I welcome everyone interested to try it, test it and to improve its code by sending comments, suggestions and GitHub pull requests. Bugs and feature requests are tracked on GitHub.
Thanks and see you soon
Sanitize filenames with PHP
Apr 25th
PDF generation and invalid characters…
While working with the TableTools PDF generator included in the great DataTables jQuery plugin I’ve noticed that sometimes the script failed to generate the PDF file. The cause? Invalid characters in the filename.
Well, to solve this issue I’ve made a simple PHP function to return a safe version of the given filename.
How it works?
Reads a filename string and replace each “dangerous” character with an underscore. Of course you can use any other “safe” character instead of an underscore.
The Code
/**
* Helper holds a collection of static methods, useful for generic purposes
*
* @author Vítor Brandão <noisebleed@noiselabs.org>
*/
class Helper
{
/**
* Returns a safe filename, for a given platform (OS), by replacing all
* dangerous characters with an underscore.
*
* @since 0.1.0
*
* @param string $dangerous_filename The source filename to be "sanitized"
* @param string $platform The target OS
*
* @return Boolean string A safe version of the input filename
*/
public static function sanitizeFileName($dangerous_filename, $platform = 'Unix')
{
if (in_array(strtolower($platform), array('unix', 'linux'))) {
// our list of "dangerous characters", add/remove characters if necessary
$dangerous_characters = array(" ", '"', "'", "&", "/", "\\", "?", "#");
}
else {
// no OS matched? return the original filename then...
return $dangerous_filename;
}
// every forbidden character is replace by an underscore
return str_replace($dangerous_characters, '_', $dangerous_filename);
}
}
// usage:
$safe_filename = Helper::sanitizeFileName('#my unsaf&/file\name?"');
?>;
Download this and more…
This snippet and other useful [at least, I hope so] PHP methods are grouped on a git repo available via GitHub. This is also the best [and only] way to get the updated version of the code.
Go to the project’s web page on GitHub or download it right way with (you must have Git installed first):
$ git clone git://github.com/noiselabs/noiselabs-php-toolkit.git
Check UTF-8 input in PHP: only letters
Feb 18th
This is a simple way to check a UTF-8 string with PHP function preg_match in search for anything that isn’t a letter, which includes all UTF-8 letters and not just ASCII. Preg_match performs a regular match on the given input using a pattern. The pattern used tells preg_match to look for letters (\p{L}) using Unicode (/u).
The function to accomplish this could look like this:
function checkUTF8Input($input)
{
$pattern = '/^[\p{L} ]+$/u';
preg_match($pattern, $string, $matches);
if (count($matches) > 0)
return true; // String is OK (only letters)
else
return false; // String has non-utf8 letters
}
Take a look at preg_match to know more about this function used for regex operations.
How to prevent caching (force image reload) in PHP and/or JavaScript/jQuery
Feb 12th
If you are using images generated on-the-fly by a PHP script (or another server language), like I’m doing on my web application, you surely do not want images to be read from cache as your users will be seeing the same first generated image (saved into cache) and not the new generated versions.
You can play with some header commands and build a function like this…
function cacheKiller()
{
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
}
…but this will work for the whole page and not only for images.
So, to make sure the images shown are always up-to-date the simple way is to add a query section with a random number to the image URL in order to make the browser think that this is a different image, while keeping the same name.
In PHP it works like this:
// Generate a number that will never be repeated using the time function
// that "returns the current time measured in the number of seconds since
// the Unix Epoch (January 1 1970 00:00:00 GMT)"
$cachekiller = time();
// Include the generated number in the image URL

If the image URL is built using JavaScript/jQuery the Math function is good choice to generate a random number.
// Generate random number between 1 and 1000.
var cachekiller = Math.floor(Math.random()*1001);
$("#thumbnail").attr("src", "path/to/image.png?"+cachekiller);