Retrofitting PHP code to use namespaces

Using namespaces in PHP can be bit more work than it appears and in some cases will require some mass search/replace to be performed.   There is one particular scenario where that process becomes unnecessarily tedious and i will show you how to make it less so.

Quick Intro to Namespaces

Without namespaces every one of your classes must use a unique name.  Using namespaces is a no-brainer for someone from a Java background where they are called packages and you pretty much can’t code without them.  But in php world you can write entire applications without ever touching the subject. Namespaces provide a way to group Classes into logical groups or modules.

Here are two PersonalBio classes without using namespaces. Since the class names have to be unique the naming gets messy.

Same class definitions using namespaces would look like this

Using namespaces allows the class names to be more generic and short. It also prevents conflicts with other libraries and built in classes.
A good example of this would be a class called Directory. Since Directory is a built-in php class you cannot have your own without specifying a namespace:

This will not work due to a conflict with an existing php class:

Same class is ok within a namespace:

The Retrofit Process
The easiest way to retrofit the existing code is to use en editor such as Notepad++ and perform regular expression replacements.
For instance, when referencing classes that don't have a namespace from a class with a namespace you will be faced with a problem of having to prefix all those references with a backslash.  There is currently no other easy reliable way to do this:

Use the following search and replace patterns:
Search:
(\bFirstClassWithoutNamespace\b|\bSecondClassWithoutNamespace\b)
Replace With:
\\$1
The "\b" determines the word boundary and the "|" allows you to replace multiple classes at a time.  This comes in very handy when there are dozens.
This is the result:

<?php namespace MyApp; class Test { $instance1 = new \FirstClassWithoutNamespace(); $instance2 = new \SecondClassWithoutNamespace(); } You can do similar replacements for classes using namespaces: Search: (\bFirstClass\b|\bSecondClass\b) Replace With: \\SomeOtherNamespace\\$1 And the result: