Archive for the ‘PHP’ Category

UPDATED: PHP Snake Case To Camel Case

Posted on March 20th, 2009 in PHP, Web Development | 1 Comment »

For anyone interested in converting snake_case_strings into CamelCaseStrings, here’s a quick php snippet to do it:

* Take a string_like_this and return a StringLikeThis
* @param string
* @return string
function _snakeToCamel($val) {
return str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));

Or if you prefer the inline thing…

$val = 'snake_case_string';
$val = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
echo $val; // Output: SnakeCaseString

Update: Back To CamelCaseString

The popularity of this post has prompted the natural question on how to go from snake_case_string to the camel case version – SnakeCaseString. This gives me the opportunity to make use of a little known feature of php, the create_function function which allows you to make inline, anonymous, functions and use them as parameters. Take a look at this function to see it in use.

function _camelToSnake($val) {
return preg_replace_callback('/[A-Z]/',
create_function('$match', 'return "_" . strtolower($match[0]);'),

ANOTHER UPDATE: Some people want to get a stringLikeThis rather than a StringLikeThis – keeping the first letter lowercase. This is actually a little trickier to accomplish because there is no lcfirst() function like there is a ucfirst() function [NOTE: lcfirst() is coming in PHP 5.3]. So here is an updated function that returns your camelCaseValue starting with a lowercase letter.

function _snakeToCamel($val) {
$val = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
$val = strtolower(substr($val,0,1)).substr($val,1);
return $val;

Vim: How To Fold Functions

Posted on March 20th, 2009 in Everyday Tips, PHP, Vim, Web Development | No Comments »

Vi Gang Sign

The is really a tip on how to fold any code block including functions. Navigate your cursor somewhere inside of the code block you want to fold, make sure you are in command/normal mode (press escape if you need to) then type zfa}

To save your folds between vim sessions you need to issue the command :mkview otherwise when you close vim your folds will be lost (your folds, not your code). To make life easier on you, you can have your folds automatically saved for you by adding this to your .vimrc file

au BufWinLeave * mkview
au BufWinEnter * silent loadview

Recursive searching in vim with grep – vimgrep

Posted on February 17th, 2009 in Everyday Tips, PHP, Ubuntu, Vim, Web Development | 1 Comment »

Vi Gang Sign

One of the smartest people I’ve ever digitally met, Ryan Paul, taught me this awesome tip for doing a project wide search in vim. I needed to look for all occurrences of the patter _Models_ in a PHP project I was working on and you can do it right inside of vim – the best text editor ever invented.

  1. Open vim and make sure you are in the top level folder of your project by typing :pwd
  2. Then type :vimgrep YourPattern **/*.php
  3. To open your search results in their own buffer type :copen

The **/ recursively searches through all your directories for you pattern. :copen opens the search results in their own buffer. You can use the arrow keys to move up and down through the list and hit enter to have it open that result in the main buffer. You can also use :cnext and :cprev to move to the next and previous items in the list. Perhaps you might bind those to keyboard shortcuts so you can move through the search results quickly.

Recursively Delete A Non-Empty Directory With PHP5

Posted on November 26th, 2008 in PHP | 1 Comment »

There are bunches of examples on how to delete non-empty directories in PHP but none of the examples that I’ve seen take advantage of PHP5′s RecursiveDirectoryIterator which makes this an almost trivial task. If you haven’t already, please check out the SPL Standard PHP Library Classes. I keep a class of static utility functions and here is my function to delete non-empty directories recursively.

public static function deleteDir($dir) {
    $iterator = new RecursiveDirectoryIterator($dir);
    foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
      if ($file->isDir()) {
      } else {

Please note the RecursiveIteratorIterator::CHILD_FIRST parameter. Without that the listing will not be in the correct order. As you iterate along you will end up trying to delete directories before they are empty. This CHILD_FIRST parameter was added with PHP 5.1 so make sure you have at least that version installed before using this technique.

Zend_Db_Table Not Returning Last Insert Id

Posted on November 3rd, 2008 in PHP, Web Development, Zend Framework | 4 Comments »

I just discovered a significant “gotcha” debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren’t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array that you are inserting does not have an empty string or a zero set in the primary key field. So, if your primary key column in your database is `id` then this will cause you problems:

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>'', 'color'=>'blue', 'size'=>'large');
$id = $table->insert($data);
echo $id; // --> will print an empty string

If you have to include the name of your primary key column as a key in the array you are tyring to insert, make sure it’s set to null NOT an empty string or zero.

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>null, 'color'=>'blue', 'size'=>'large')'
$id = $table->insert($data);
echo $id; // --> will print the id of the newly inserted row

The reason for this is line 822 in the Zend_Db_Table_Abstract class:

if ($this->_sequence === true && !isset($data[$pkIdentity])) {
  $data[$pkIdentity] = $this->_db->lastInsertId();

Notice the isset() condition. If primary key value in the data array you are inserting contains anything other than null then isset() will return true causing the lastInsertId() function to not get called. Hopefully this will clear things up and save us all alot of debugging time!

Zend Framework: Redirect – The Easy Way

Posted on October 28th, 2008 in PHP, Web Development, Zend Framework | 9 Comments »

It is common to need to redirect from one controller action to another or even from one controller to another when coding with the Zend Framework. From my code reviews, I find that many people are using the _redirect() method from Zend_Controller_Action. This function takes a url and an optional array of options. This is a fine choice if you need to redirect to a completely different website but the vast majority of redirect in a web application is to another action within the same application.

The lesser known, and much easier, way to redirect within the Zend Framework is to use the Redirector Zend Controller Action Helper

The syntax is much easier since you don’t have to reconstruct a complete url, you just pass in the action and controller names. In fact, the only required parameter is the name of the action. If only an action name is given then the current controller is assumed to be the target controller. Here is a quick example.

_helper->redirector('target', 'example');
    // NOTE: 'example' is optional since the default target controller
    // is the current controller

  public function targetAction() {
    // Do some things...


Zend Framework: How To Disable A View In An Action

Posted on September 17th, 2008 in PHP, Web Development, Zend Framework | 3 Comments »

Sometimes, especially when just testing things out, I don’t want to go to the trouble of having to create view script for my Controller Action and instead I just want to print something to the screen right from my Controller Action function. I guess because it’s sort of hard to find out how to do this in the ZF Documentation this is one of the most common questions I get asked – even from somewhat seasoned developers. The answer is in the Controller documentation and it’s easy to think that you ought to search under the View documentation to figure out how to turn this stuff off. Whatever the case, here’s the trick.

Read the rest of this entry »

PHPDoc – How To Continue Comments In TextMate

Posted on August 21st, 2008 in CodeIgniter, Mac OSX, PHP, Web Development | 1 Comment »

When using TextMate to code PHP, you may be annoyed by the way TextMate handles hitting the Enter key while in a PHP comment block. I would like the lead * to be continued on the new line. There are two ways to get this to happen.

Read the rest of this entry »

Overloading So That empty() works in PHP

Posted on August 13th, 2008 in PHP, Web Development | 2 Comments »

Overloading PHP So That empty() Works

PHP5 has a much improved object oriented feature set. With great MVC PHP frameworks such as CodeIgniter, CakePHP, and the Zend Framework you should certainly be writing your own classes and taking advantage of objects in your coding. Using the magic methods that you get with PHP5 you can overload your classes so that you can do some very cool stuff.

PHP’s overloading deviates from the way other programming languages work. Overloading in most other languages enables you to define several different methods all with the same name but taking different types of paramters. PHP, on the other hand, uses overloading to handle calls to object members or methods that have not been defined or are not visible in the current scope of the caller.

A Quick Example Of Overloading

Read the rest of this entry » PHP Screencast Tutorials

Posted on August 5th, 2008 in CodeIgniter, PHP, Web Development | 1 Comment »

PHP Screencasts, PDF books, and source code. Lessons will be cover PHP Development, and the CodeIgniter PHP Framework.

As of today, is open. If you register during the beta phase, you will receive a 50% discount on all of the lessons that will ever be published.

Lesson Topics Will Include

  • Object Oriented Programming in PHP5
  • Setting Up A CodeIgniter Project
  • Understanding MVC Architecture
  • Using Your Own Libraries With CodeIgniter
  • Working with Sessions
  • Databases and CodeIgniter
  • Working With Forms
  • Sending Email
  • Testing Your Code
  • And more…

Sign up today to lock in your discount.

Get Adobe Flash playerPlugin by wordpress themes