Better sprintf: CakePHP String::insert

September 16, 2010

Today I was re-factoring my code a bit and in some places decided that string concatenation needs to go. Simple example:

<?php
  echo $html->link(
    __('Download', true),
    '/'.$material['dir'].'/'.$material['filename']
  );
?>
Easy answer is sprintf:
<?php
  echo $html->link(
    __('Download', true),
    sprintf(
      '/%s/%s',
      $material['dir'],
      $material['filename']
    )
  );
?>
But this isn’t very descriptive. String::insert does it the proper way:
<?php
  echo $html->link(
    __('Download', true),
    String::insert(
      '/:dir/:name',
      array(
        'dir' => $material['dir'],
        'name' => $material['filename']
      )
    )
  );
?>
Now that’s elegance.