Monthly Archive for January, 2008

observe_field in symfony and it’s options

While looking for possible options for the observe_field() helper in symfony, I noticed there wasn’t a lot of documentation around to describe what the possible options are to pass to it. After a bit of searching, I found what I wanted and thought I’d share it in case someone else would need a similar thing:

<tr>
  <th>IP:</th>
  <td>
        < ?php echo object_input_tag($server, 'getMainIp') ?>
        <div id="valid_ip"></div>
        < ?php echo observe_field('main_ip', array(
                'url' => '@lookup_ip',
                'frequency' => 3,
                'update' => 'valid_ip',
                'with' => "'ip='+$('main_ip').value",
                'loading' => "Element.show('indicator')",
                'complete' => "Element.hide('indicator');"
        )) ?>
        <div id="indicator" style="display:none"></div>
  </td>
</tr>

I needed to create an input field for an IP. If you want to change the IP, a request should be made to check if the IP is still available or not.

What this basically does is check if the field 'main_ip' (this is the object_input_tag() field) changes, and it does that every 3 seconds. If it has changed, we go to the url '@lookup_ip' and pass it one parameter, named ‘ip’ with the value of the input field we are observing. During loading the request, we show an indicator that we’re loading in the background, and if the request is complete, the indicator is hidden and the div 'valid_ip' is filled with the output of our action.

Pretty easy if you have a look at the code, but there aren’t much docs around that give examples for this. A good resource for these things is the Symfony JS and Ajax cheat sheet you can find here. (I chose the english version ;))

Exception catcher filter for Symfony

Update: Updated the class to have a cleaner code syntax.

Recently, I needed a different way of processing my own defined exceptions in symfony. The cleanest solution was to implement a symfony filter, as I didn’t feel like try-catching every action available in my application :)

First thing to do is let symfony know when we can enable the filter.
Edit apps//config/app.yml and add the following:

all:
.global:
  exceptionCatcherFilter: on

Next up is writing the actual filter.
Create apps//lib/exceptionCatcherFilter.class.php:

class ExceptionCatcherFilter extends sfFilter
{
    public function execute($filterChain)
    {
       if (sfConfig::get('app_exceptionCatcherFilter')) {
           try {
               $filterChain->execute();
           } catch (sfStopException $e) {
               // This is an internally used symfony exception and shouldn't be blocked
               throw $e;
           } catch (Exception $e) {
                // Do something with the exception, other than just throwing it
           }
       } else {
           $filterChain->execute();
       }
    }
}

Basically, this checks if we have enabled our custom filter, then tries to execute it. If it does throw an exception, the exception gets catched. When the exception is not of class ’sfStopException’, we can do something with it (for example, log it to a database or send mails or whatever). If we don’t have the filter enabled, the chain should still move on and pass execution to the next filter in the chain.

Last step that needs to be done is placing our filter somewhere in the chain of filters that is active in our application.
Edit apps//config/filters.yml:

rendering: ~
web_debug: ~
security:  ~
exceptionCatcherFilter:
class: ExceptionCatcherFilter
cache:     ~
common:    ~
flash:     ~
execution: ~

This is, of course, a very simple version of such a filter but it does the job and can easily be extended to do whatever you need.
The current context is retrieved by: $this->getContext();, so you should have a look at that too.

iTunes music sharing in Linux with Banshee and DAAP

This one is actually much simpler than I’ve anticipated. It’s what needs to be done if you are on Linux and want to share your music with the ‘Bonjour’ protocol from Apple, to make your music appear on another computer in iTunes as shared music. You don’t need the iTunes application for sharing, a music player / manager supporting the DAAP protocol will do just fine. In this example, I use the Banshee music player for gnome under Ubuntu 7.10.

It basically comes down to this line:

# apt-get install banshee banshee-daap

Then, go to the Edit -> Plugins menu item, set the ‘Music Sharing’ plugin active and have a look at the settings of the plugin to see how it can be configured (Not much to it, though).

Funny Rails trac ticket

This is just too funny not to blog about:
http://dev.rubyonrails.org/ticket/10919

be sure to read the attachment right and have a look at the comments :)

PHP Array syntax: array() vs []

Currently there is a funny discussion going on on the php.internals mailing list (Not the first time though). It’s a debate about the syntax of the array notation.
At the moment, when you want to create an array, you’d write:

$myArray = array(); // To initialize it
$myArray = array('value', 'foo', 'bar'); // Initialize, and fill it right away

What now gets proposed, is a shorter notation (some would say, more Javascript-like):

$myNewArray = [];
$myNewArray = ['value', 'foo', 'bar'];

I could probably say I’m in favor of adding the extra array syntax, as it shortens the notation for something as trivial as an array.

2 remarks I have about this, one in favour and one against it:

  • The array() notation as it currently is, is a bit ambiguous. It looks like a function but it’s not. The square brackets notation would be more consistent.
  • As Marcus told, somehow the ‘[]‘ array feels not so PHP like… This might be very subjective though.

MacHeist bundle, get it while it’s hot

In case you didn’t heard the buzz yet about MacHeist:

Check out the mac application bundle you can get for a very low price. Currently, there are 14 unlocked applications for only $49. The normal price of the apps altogether would be around $500, so it’s definitely worth checking out! Referrers get an extra bonus, so by using the link to the application bundle above, you would be making me happy :)

And what’s more, aside from supporting the indie mac developer, 25% of your purchase goes to a charity of your choice. Ain’t that cool or what? Only 2 days left to order, so be quick if you have your mind set on some of those applications.

To give an example of what you’ll be getting: CSSEdit, AppZapper, Speed Download, iStopMotion, Wingnuts 2 and more.

PHP Constants, the lesser known ones

Often, when looking into people’s code, I find little code fragments that could be designed a bit more elegant. Sometimes the code needs refactoring or sometimes some design patterns needs to be applied.
This time though, I’d like to look at some PHP constants that are lesser known, but can make your code cleaner, less error-prone and more portable.

PHP_EOL:

Returns a line ending (EOL = End Of Line), depending on the operating system you run your code on.

$greeting = 'hello world';
$name = 'felix';
echo $greeting . PHP_EOL . $name;
 
#outputs:
hello world
felix

DIRECTORY_SEPARATOR:

Returns the directory separator for the current operating system. On Linux this is ‘/’, but for example on a mac, this is ‘:’. Using DIRECTORY_SEPARATOR increases portability of your code.

$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'site.class.php';

PHP_INT_MAX:

Returns the upper bound value an integer can hold for the current operating system. Values will be different on 32-bit or 64-bit systems, so when dealing with large numbers on different hardware systems, take this in consideration.

PHP_OS:

Returns the operating system that PHP is installed on.

if (PHP_OS == 'Linux') {
echo 'yay, linux!';
} else {
echo 'ugh, windows..';
}

PHP_SAPI:

Returns the SAPI that you’re currently using. This is the same as the PHP function php_sapi_name(), but supposedly should work a bit faster, because there is no need for a function call. PHP_SAPI can be interesting if you want to write code that runs on either a website or independently on PHP Commandline (in which case, PHP_SAPI outputs CLI or CGI).

// Check if we're running commandline,
// in which case we can thread our application
if (substr(PHP_SAPI, 0, 3) == 'cli') {
$pid = pcntl_fork();
// ...
}

PHP Abstract podcast about Symfony

 PHPAbstract has a cool podcast up about the symfony framework. This is presented by Stefan Koopmanschap, web application developer at Ibuildings.nl.

His podcast is a brief introduction to symfony, what programming principles it uses, why it can be an advantage for you to deploy your project with symfony and more. A brief and interesting introduction talk to symfony.

The link to the podcast can be found here.

Installing symfony in a subdirectory of your documentroot

I recently needed to set up a Symfony install without a separate virtual host, so as a subdirectory of the (Apache) DocumentRoot directory (like: http://www.example.com/symfony/).

As you may know, symfony appreciates it when it has a reserved virtual host for itself, but also provides ways to just install it in a separate directory. The following steps need to be taken:

1. Change the apps/<yourapp>/config/settings.yml file and set relative_url_root


all:
  .setttings:
    relative_url_root: /subdir

2. Go to your front controller’s .htaccess file (usually in web/) and modify the RewriteBase directive


RewriteBase /subdir/

3. Optionally, if you want to omit the script name in production environment url’s, be sure to have enabled no_script_name = on in apps/<yourapp>/config/settings.yml


prod:
  .settings:
    no_script_name: on

4. If you took step 3, be sure to check if your apache installation has support for mod_rewrite enabled.

This way you can have nice url’s, like http://www.example/subdir/module/action
That’s it!

PHP Statistics for December 2007

The guys over at Nexen have their PHP statistics ready for december 2007. They give a pretty good impression on how much PHP is used on websites worldwide, and what the trends seem to be. Only one thing I found remarkable: only 27% of the servers running PHP are running PHP5! Good thing though: PHP 5.2.5 is gaining the most website increase in december, so we’re going the right way!

I’d say, with 19 days to go until PHP4 will reach end-of-life, three quarters of the PHP-using world better start making the switch :)