Using a namespace for your functions and classes

An often made mistake by WordPress developers is to use to generic function and class names. For instance, if you're building a plugin to do with YouTube, using a class name "Youtube" is bound to cause issues: if a user has multiple plugins dealing with Youtube, he or she could very well end up with two plugins that have a class Youtube, which would immediately cause a crash. The only way of fixing that would be to remove either of the two plugins.

The best thing to do in these cases is to use one or more classes for your plugin, and to use a namespace for these. So, for instance, a class called "YoastYoutube" instead of "Youtube". One of the benefits of using a class is that the function names within that class can be short and concise and need not be namespace. So you could have a function get(), within that class, and it would never break anything.

This is also valid for other instances where your chosen names might collide: custom taxonomies and custom post types, widget names and also specific hooks for actions and filters that you add to your plugin or theme.


Category:
You can skip to the end and leave a response.

5 Responses to “Using a namespace for your functions and classes

Indeed, it happens too often! I've found this out the hard way myself ;-) Thanks for pointing this out!

Greets, Sander

So simple, yet so few plugin developers seem to do this correctly. Although I'm seeing more namespacing in the plugins which are 2010 and newer, or under active development. Older plugins, not so much.

Very informative. I'll stay away from it.
Thanks

Ironic sidenote here is that developers who are NOT using classes or namespaces for their plugins cannot even have two plugins of their own activated on the same install. :))

long gone are the old days of my_special_function_that_wont_conflict_with_other_plugin_function_name() functions, so much easier to read code this way!

mind you, my opinion, the long functions do have their benefits on occasion if used sparingly

Leave a Reply

Comment Rules

You can use: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


You have to use a valid email address. If you've not commented here before, you'll receive a confirmation email to make sure your email address is valid and working, clicking the link in that email will immediately post your comment.


Links in comments that are not related to the topic (such as "signature links") will be deleted. Using keywords instead of your real name will lead to the comment being deleted. Anonymous commenting is not allowed either.