Category Archives: Programming

Top 5 Script Kiddie Mistakes

These are the most common and most annoying mistakes I see in web development code on a daily basis. Well, Ok, it’s the things that annoyed me most TODAY, but it’s not unique. It’s mostly PHP and MySQL stuff here, but the same abuses take place anywhere the language allows it.

1. Database prefixes. I find so many database tables that use a “table” or a “tbl” prefix. Are you serious? Do you think we don’t already know it’s a table we’re looking at? Likewise, some developers find it somehow necessary to use “column” or “col” in their column names. I mean really… do you pin your own name upside down on your shirt? Seriously, this type of labeling is completely unnecessary and it probably reveals you as the half-baked amateur that you are. Label your column names descriptively: too little info is bad, but too much is no better.

The one exception I make to this rule is this: be verbose with your primary keys because you’ll use those in all of your join statements. I know it’s easier to code if every table uses the ubiquitous “id” as the primary key, but if you ever have to do complex MySQL joins for reporting queries you’ll appreciate the fact that user_id or post_id references the same thing no matter which table it’s used in. Continue reading Top 5 Script Kiddie Mistakes

WordPress vs. MODx

There are a lot of Content Management Systems (CMS’s) out there, so I wanted to give a blow-by-blow analysis comparing two of them: MODx and WordPress. I feel oddly qualified to do so: Brian and I just authored a book on WordPress plugin plugin development (WordPress 3 Plugin Development), and I am a MODx Solution Partner who was invited to speak at the MODxpo conference in Dallas last year. I’ve used both flavors of MODx (Evolution and Revolution) and WordPress while building somewhere around 50 web sites over the past couple years, and I like both systems. I have even contributed a couple plugins for both systems (e.g. Custom Content Type Manager for WordPress). So after the urging of some friends and colleagues (like Kris), I’m organizing my techno-ramblings into a coherent article.

I’m going to walk through a series of areas and compare and contrast both how both CMSs work in those areas. The comments here apply to WordPress 3.x and (mostly) to MODx Revolution, but MODx Evolution is mentioned where appropriate.

Basic Stuff

System Requirements

WordPress 3.1 MODx Revolution
Server OS ???
  • Linux x86, x86-64
  • Windows XP
  • Mac OS X
Web Server
  • Apache ???
  • NGINX ???
  • Apache 1.3.x or Apache 2.2.x
  • IIS 6.0+
  • Zeus
  • lighthttpd
  • Cherokee
  • NGINX
Database
  • MySQL 4.1.20 or higher (5.0+ recommended)
  • SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP privileges
  • MyISAM table types
  • MySQL 4.1.20 or higher (excludes 5.0.51)
  • Default table encoding of UTF-8
  • SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP privileges
  • InnoDB and MyISAM table types
PHP Version 4.3+ (5.2+ recommended) 5.1.1+ (excluding 5.1.6/5.2.0)
 

  • Running as FastCGI
  • safe_mode off
  • register_globals off
  • magic_quotes_gpc off
  • PHP memory_limit 24MB or more

PHP Modules ???
  • zlib
  • JSON
  • cURL
  • ImageMagick
  • GD lib
  • PDO, with database driver
  • SimpleXML

*Source: WordPress requirements, MODx requirements

If the requirements for MODx Revo look insanely detailed, ask yourself this: “do you really want to be guessing whether or not your server will support a given app?” MODx Revo does a pretty good job of testing for the necessary requirements during installation, so you don’t have any unexpected surprises.

Installation

WordPress offers its “famous” 5-minute install, and I give them credit where credit is due: WordPress is a simple web app to install, but to be fair, installing MODx Evolution is also very straightforward.

MODx Revolution has beefier requirements, and it’s far more likely you’ll run into troubles setting up your webserver permissions or PHP extensions (e.g. PDO). Moving a Revolution install to a new server is also a tricky operation that requires some patience (see this how-to).

Summary

In short, WordPress and MODx Evolution are easily installed on practically any web server that supports PHP and MySQL. MODx Revo takes longer to install and configure and it requires a beefier server.

Templating

Hands down, MODx offers the gold standard in templating. Expression Engine is a healthy second place, but only in my days of doing Perl development with the venerable Template Toolkit did I encounter a templating system that followed good MVC architectural principles as well as MODx.

What does that mean? It means that if you’re a front-end designer who likes to roll your own HTML and CSS, then MODx will grant you total freedom to implement the designs you want, whereas WordPress may result in headaches and holes punched in your walls (no comment on the convoluted mess that is Drupal and Joomla templates). I’ve posted previously about creating templates in MODx Evolution and how to import existing layouts into MODx Evolution, and the process in MODx Revolution is nearly identical (the only difference is the format of the placeholders).

In MODx, you can easily have multiple templates (i.e. layouts), and use any one of them for any page. In WordPress, the ability to use a specific template is possible only with pages, not posts. The thing that really gives me convulsions is understanding how WordPress formats its special pages, e.g. a category page, or an author page. See the image below as a reference for how WordPress formats page requests.

WordPress Template Hierarchy
WordPress Template Hierarchy

See the official WordPress docs for Template Hierarchy for more information. I honestly have a hard time fathoming that this is the solution that actually got implemented… what other crazy ideas were on the drawing board?

Summary

If having a specific HTML/CSS layout for your site is more than a “nice-to-have”, then MODx will save you many hours; the time to rework layouts in WordPress can be considerable and some of the PHP hacks are not trivial, whereas MODx templates are easy to create, modify, and maintain.

Menus

MODx offers nearly infinite menu flexibility through use of menu-generating PHP Snippets, primarily WayFinder, but it’s not aimed at the average user. WordPress has a built-in GUI for creating menus, but I have experienced some bugs with it when using custom content types. Your WordPress theme may not support more than one or two menus, so in the end you may end up writing some code in your tmeplates (e.g. using my Summarize Posts plugin) so you can list the posts that you want to see.

In a nutshell, WordPress offers an easy GUI, but if you need more customization MODx’s flexibility here is far greater.

Plugins

WordPress has a huge number of user-contributed plugins available, whereas MODx has relatively few. The sheer number is not a good comparison, however; I downloaded and tested hundreds of plugins in the process of writing my WordPress book, and the number of plugins that are unusable due to sophmoric errors or plain-old bad coding is huge. I estimate that at least half of the plugins in the WordPress repository are unusable, and perhaps only a tenth of them are worth using. There are crufty plugins in the MODx repo to be sure, but the playing field is more even than you might think.

The real difference here comes when you have to write your own code: MODx is a lot easier to work with with a shorter learning curve for a majority of code, whereas learning the ropes of WordPress plugins requires more guidance (hey, did I mention we wrote a book about that?).

Architecture

This is an area that is hard to discuss unless you’re a geek, but in a word, MODx offers a robust and well-architected MVC framework under the hood that can make writing custom plugins (Snippets, manager pages, et al) a breeze. The work done by Jason Coward and Shaun McCormick is really astounding.

Some of the limitations to WordPress are really staggering: it is basically a stateless application, so by default it does not use sessions, and nearly all of its API functions exist as procedural functions in the main namespace, so naming collisions are a big concern when authoring plugins. This makes certain functionality damn near impossible in WordPress. For example, creating a WordPress application with a login portal and access to custom data models would require an enormous amount of time. Even accessing WordPress’s posts and categories is difficult at times; I basically had to rewrite core WordPress functionality with another plugin (Summarize Posts) just to get the menus and summaries I needed for one recent site.

Another severe limitation is WordPress is that all extensions to the core occur via plugins that are triggered by system events (confusingly they are loosely categorized into “actions” and “filters”). This construct can be awkward at times, and the WordPress architecture is showing its age as the number of events exponentially increases, whereas the amount of documentation for them continually wanes. Realistically you can get WordPress plugins to do just about everything you need using only a handful of events, but debugging someone else’s plugins is a nightmare: there is no centralized location listing which events are being hooked into, and new events are often created and executed on the fly. Debugging WordPress plugins is like Alice’s trip down the rabbit hole: majorly trippy,and you don’t know if you’ll ever come out.

User management is another area where MODx dwarfs WordPress: Revolution can handle totally granular control of permissions, but it is admittedly overly complex for 90%+ of use cases. Evolution offers a much more sensible permissions scheme that covers most use cases.

MODx offers much more sensible implementations of custom code: like WordPress it uses event-driven plugins, but it also uses custom PHP snippets which can be placed anywhere on a page or in a template.

Another impressive feat is how MODx Revolution has abstracted the database into a separate coding layer — that means it is relatively easy to interface with custom database tables (or even to other database engines) using code that is completely database agnostic (support for SQLite and PostGREs is in the works). That’s some seriously geeky stuff that has kept me awake at night trying to comprehend how they accomplished that. MicroSoft has even worked directly with the MODx team because MODx’s architecture is flexible enough that it can run on an all MicroSoft stack (i.e. IIS and MS-SQL). I can’t think of a single other system that switch-hits as well as MODx.

Summary

If the site you are building is more of a web application that requires a lot of custom coding, go with MODx; the level of maturity in the underlying MODx framework is light years ahead of WordPress, but be advised that the coding in MODx is sometimes so advanced, it takes a very senior developer to understand what’s going on. If you decide to do a more serious application-type-project in WordPress, be sure to allocate extra time to augment or rewrite the core code. If you’re doing basic extensions or variations of a simple site/blog, then WordPress plugins can do that pretty well, so don’t overcomplicate things.

Dashboard

WordPress offers a clean manager dashboard for its administrators which relies on the jQuery JavaScript library to provide AJAX functionality and smooth user experience. It’s pretty easy to find your way around.

WordPress Manager dashboard
WordPress Manager dashboard

MODx underwent a huge change in its manager dashboard between Evolution and Revolution, and the Revolution dashboard is overwhelming for many. Evolution’s dashboard is cleaner and snappier.

MODx Evolution Dashboard
MODx Evolution Dashboard

MODx Revolution’s manager dashboard is still being optimized. It’s based on ExtJS. For those of you not familiar with ExtJS, it was based on YUI (the Yahoo User Interface library), and it offers some fatastically powerful features for building interfaces for web applications. My only complaint with it is that it’s heavy: the MODx Revo dashboard can take a long time to load, and sometimes clicking on buttons and links feels unresponsive.

MODx Revo dashboard
MODx Revo dashboard

Summary

Do not make your decision about which system to use based on the dashboard alone — that’s like marrying a girl for how big her tits are. I know some clients who have loved and hated the dashboards in both systems. Again, MODx offers more flexibility if you want to change the dashboard behavior. The big difference here is simple: WordPress gives you a super clean view of your posts based on time whereas MODx gives you a hierarchical view of your posts.

Blog

Everybody wants a blog, just like everybody wants a shiny new car. Authoring blogs has been a core competency of WordPress, and they get massive props for making them very simple to setup: out of the box, you can get a blog up and running with integrated tags and categories and comments within minutes. It’s really what WordPress is all about: blogging. WordPress even has some nice security features in place with its Akismet spam filter.

Contrary to some of the on-line murmurings out there, both versions of MODx can run blogs, but until MODX 2.2, the process to set them up was painfully laborious in comparison. The Articles extra for MODX gives you a quick and easy blog — it can even import your posts from WordPress, so the gap between the two systems is closing quickly. The only thing it doesn’t do as well as WordPress right out of the box is its taxonomies (tags and categories): you still have to do some configuration to get those configured how you want them, but as the docs say:

“MODx Revolution is not blogging software, but rather a full-blown Content Application Platform, it doesn’t come pre-packaged with a cookie-cutter blogging solution.” 

Summary

If your priority is to get a blog up and running as quickly as possible, and you have few requirements for supporting any other content, then WordPress is the way to go. Starting with MODX 2.2, however, you can use its “Articles” extra, which gives you simple blogging functionality, with many of the features available to WordPress.

Custom Content (CMS functionality)

If blogging is where WordPress shines, then CMS functionality is where MODx clearly has the upper hand. WordPress does support custom fields for its posts and pages, and in version 3.x, they support additional “post types”, so finally WordPress is getting some traction as a CMS, but it’s still a bit of a toy in comparison to MODx.

One of the biggest problems with WordPress as a CMS is its lack of support for sensible custom fields: for each post or page, you have to manually add the same custom fields over and over again, and by default, the custom fields are always simple text fields. I have attempted to rectify this in my Custom Content Type Manager plugin, and my plugin does a lot to give WordPress CMS capabilities, but it still represents a series of awkward workarounds that stretches the WordPress core nearly to its breaking point.

One related area here is how MODx can manage and serve static files via what MODx calls “Static Resources”. This is a great way to enforce permissions on viewing, streaming, or downloading static files (e.g. PDFs or Flash movies). WordPress just flat out can’t do that.

Although MODx offers greater flexibility, WordPress’ integration is a bit cleaner for the manager user (it’s a holy pain in the ass for the developer, but if you download my plugin you should avoid this unpleasantness). When WordPress registers a new “post type”, you get a nice menu icon in your dashboard and it’s really clear to the manager that he/she is adding a new post, page, or movie (etc). For example, if you want to add a movie post, you’d click on “Add Movie”. It’s really quite logical. In MODx, this same type of distinction occurs at the template level. Architecturally, this makes sense, but it’s confusing for the manager user, because it may not be at all clear that they need to add a “normal” page (i.e. resource), and then choose to use the “movie” template. I’m planning a MODx plugin to help rectify this UI “wart”.

A custom post type in WordPress
A custom post type in WordPress

Summary

If you have to display multiple types of content on your site (e.g. an eCommerce site), then MODx offers far greater flexibility, but it does take longer to configure. If your CMS requirements are simple and you don’t need to worry too much about customizations, then WordPress can do that very well and very quickly.

SEO

SEO is the an cyclical buzz, and at the moment, a lot of SEO guys are hailing WordPress as the holy grail of search-word wad-shooting. To be blunt, I think SEO is largely an over-hyped crock of crap. If you build a well-structured site with good content, your pages will show up in search results: if there is a site out there with awesome content that is not showing up in relevant search results, I have yet to see it. Search engine optimization is often a pseudo-science practiced by get-rich-quick marketeers who are convinced that they can turn lead into gold by over-hyping a site with various gimmicks. 90% or more of SEO should have to do with creating good content, and perhaps the last 10% of your efforts should go into polishing your site. It can be used to improve search results, but it tends to fail when you try to make search results come out of thin air. Too often I have seen companies do this the wrong way around: they spend 90% of their time publicizing a site that is a vapid cesspool instead of spending their time making a site that’s worth visiting. At best, SEO techniques are constantly changing as Google updates and refines their indexing algorithms. If you optimize your site today and Google farts tomorrow, all of your work may be for naught. Do your due dilligence, but it’s just not worth spending inordinate amounts of time tring to beat Google at their own game.

Rants aside, both systems offer ample ways to do search engine optimization. Assuming that you have good content, the rest of the process boils down to having well structured HTML (which relies on a solid templating system), and the ability to effectively index your pages. WordPress offers built-in taxonomies (categories and tags) for flagging your posts, and MODx can be set up to do this rather easily by using an Auto-Tag custom field (a.k.a. a MODx “Template Variable”).

MODx offers a much more flexible system for generating URLs (basically you can use any URL you want for any page). WordPress does offer flexibility here, except for its special pages (e.g. category listings or author pages).

Summary

Comparing SEO features between MODx and WordPress is a moot point: both systems allow you to adequately structure your content and your site.

Security

No system is 100% secure. MODx has had relatively few serious exploits; WordPress has had many, no doubt due in part to its popularity. For what it’s worth, I have had WordPress and MODx Evolution sites hacked, but not yet a Revolution site. It’s hard to quantify how secure an application is… I’d love to see the detailed forensic results of a penetration test against default installations of both CMS’s. In general though, the WordPress architecture is primitive and more ripe for being hacked: it’s more difficult to lock down spaghetti code. WordPress also offers many more plugins, and the plugin authors tend to be less experienced, so their code is more likely to have security holes.

There are many fingerprinting utilities out there that will attempt to locate known weaknesses in plugins, and WordPress is more easily fingerprinted; MODx Revo allows you to change default locations for the MODx manager or to even remove it from public view altogether. There are some discussions in the MODx Forums about how to harden MODx, but I haven’t yet seen a detailed how-to on how to eliminate the most common attack vectors. There are also good posts out there for hardening WordPress.

I reported a nasty vulnerability in phpThumb that affected MODx and numerous other CMS’s (phpThumb is a popular image manipulation library), but the MODx Revo architecture prevented the exploit from succeeding on Revo (good job to Shaun and Jason for architecting the connectors in the way they did).

Summary

I feel that MODx Revolution is probably more secure, but there are no guarantees when it comes to security. No system is bulletproof, so you best have redundant backups on hand and follow the recommendations of Basic Web Security no matter which system you’re on.

Support

This is another area that is pretty black and white in my opinion: WordPress support sucks. Although WordPress is more popular if you look at the numbers, you wouldn’t know it if you post questions in the WordPress Forums. I have rarely gotten any useful answers (if I got answers at all): anything beyond simple inquiries tend to go unanswered, leaving me alone in the dark reverse-engineering damn near everything.

My other gripe with WordPres is their weird distinction between WordPress.com and WordPress.org. You can host your blog at WordPress.com, and then you get more support, but it is effectively software as service: you can’t upload plugins and you can’t modify code, so the interface suddenly becomes a bit like BlogSpot.

By contrast, the MODx Forums are full of helpful people. It’s a great place to be: it’s not uncommon to get responses from the core team on almost any level of inquiry, from trivial to cerebral meltdowns. There are some superstar participants, such as Susan Ottwell and Bob Ray, who have both contributed immensely helpful posts and tutorials on how to use MODx. MODx also offers commercial support; it’s still in its infancy, but for a yearly fee, you can get access to a kind of “MODx hotline” and get help resolving MODx issues on your sites.

Documentation

In the same breath as support, I must mention documentation. In general, documentation for both systems is lacking, in some areas painfully so. While using WordPress, I have often I have searched for hours trying to find a way to do a certain thing, only to end up grepping through the code base and deciphering the raw code myself. Frequently the official documentation has holes or in some cases, it’s just plain wrong. The best resources for some advanced WordPress features are blogs written other developers.

MODx’s documentation is also frustratingly AWOL on a number of topics, but least the MODx code base is integrated with a standard documentation publishing system so if needed you can see for yourself how the functions are structured without having to grep through the code base. The vibrant MODx forums fill in a lot of the holes in the documentation, and that’s a huge benefit for any open-source project.

Summary

If you need support for your site, especially guaranteed support, then only MODx offers a paid support service; WordPress doesn’t offer a paid support option.

Scalability

WordPress can handle a huge number of posts, but it does get bogged down with a large number of pages, and there are lots of whisperings about this (e.g. here). I suspect it has to do with WordPress’ convoluted templating system (see above), which makes me wonder what the limits are on custom post types.

MODx Evolution suffered from a limit of approximately 5000 resources (in MODx, pages and posts are types of resources), but that limit has been corrected in an upcoming release thanks largely to the efforts of Charlie over at ProWebscape.com.

MODx Revolution has no such limits: it offers a great built-in caching system that allows it to serve pages very quickly. It has been benchmarked as twice as fast as Expression Engine (see this blog post).

More importantly, MODx Revolution was built with scaling in mind: it stores session data in the database, so it is easily deployed on load-balanced servers. This is hugely important if you are building a site that might one day get massive amounts of traffic; WordPress can be deployed like this, but such usage is not generally anticipated. I don’t know of many large commercial sites running WordPress (in fact, I only found one: 9rules.com).

Summary

MODx is by far the more mature option here if you anticipate building a large site.

Conclusion

I do like both systems, and I use them both daily. WordPress has a much lighter footprint and is easier to use for a large number of use-cases: if you just need to get a site out the door fast, then WordPress is really hard to beat. WordPress is plug-and-play for just about everything and that saves you hours of setup time, so it can be the right solution for a majority of sites. But the more customizations you require (particularly in scripts or in layouts), then the more appealing MODx becomes: WordPress has thousands of plugins available, but if those aren’t meeting your needs, I’ve found certain types of customizations to be extremely difficult in WordPress whereas most often, MODx handles them with ease. Doing things like building web applications with strict formatting requirements is much easier in MODx because it’s built more as a launchpad for customizations: it’s really more of a content management framework (CMF). MODx Evolution is the best system I’ve used for building small to medium sized informational/brochure sites, WordPress rules as the blogging king, and I’ve been very impressed with how easily I can build web applications using MODx Revolution. There isn’t one tool that’s right for every job; the more projects you complete, the better idea you’ll have as to which system will accomplish your requirements more easily, and hopefully this article helps you spot more of what each system is good at.

Releasing New Versions of your WordPress Plugins

If you are a WordPress plugin developer, then this post is for you. There is very little documentation on how to effectively use the WordPress Subversion repository, and the repo architecture is critically flawed in its structure making “kosher” usage seem entirely buggy. Worse yet, the support in the WordPress forums is practically non-existant. For a more thorough explanation of this process, see our book on WordPress 3 Plugin Development Essentials, which features an entire chapter on dealing with SVN and the WordPress repository.

Below is the short summary of what is presented in the video.

How to release updates to your WordPress plugin (quickie version)

  1. Make the updates to your code, fix any errors, add new features.
  2. Update your plugin’s main file (the one with the information header) so that it references the new version of your plugin, e.g.
    Version: 0.5
  3. Update your readme.txt file to describe the changes you have made, but DO NOT change the Stable Tag. This number must point to an existing directory inside your repo’s tags directory.
  4. Save your files, then commit your changes to the SVN repo, e.g. svn commit . -m "My new version is ready"
  5. Tag the new version using the SVN copy command to copy the trunk new a new numbered directory in tags, e.g. svn copy http://plugins.svn.wordpress.org/your-plugin/trunk http://plugins.svn.wordpress.org/your-plugin/tags/0.5
    Remember: the tagging operation is just a copy operation.
  6. By performing the tagging (i.e. copy) operation, a new directory has been created inside the tags directory. So only now can you safely update your readme.txt file’s Stable Tag, e.g.
    Stable tag: 0.5
    That number acts as a pointer to the corresponding folder inside of the tags directory (it would point to http://plugins.svn.wordpress.org/your-plugin/tags/0.5 in this example).
  7. Commit your changes to the readme.txt file. This will ensure that the Stable Tag attribute points to the newly created version: svn commit . -m "Updating the stable tag"
  8. You should be done now, but the WordPress SVN repository has been so problematic…. keep an eye on your plugin’s download page and verify that the changes get picked up. The changes should be picked up within 15 minutes or so… if they don’t get picked up, look at the downloaded zip file carefully… does the link say one thing but the name of the zip file says something else? It’s easy to mix things up, so if you get stuck, try reviewing the steps here.

How to release updates to your WordPress plugin (Long Version)

Ok, that was too quick? Well, we left out some important geeky points. The way WordPress’ download page works is that it looks at the readme.txt file at the HEAD of the repo, and then it follows the value listed there for Stable tag. If the Stable tag lists version 0.8, then the information from tags/0.8/readme.txt is used to generate your plugin’s information page and the files in tags/0.8 are packaged up into a zip file and that’s what downloads when the user clicks the download link.

Can you see the problem with this setup? Normally, when you tag a directory in SVN, that copy is treated as a read-only reference, but in this setup, it is frequently easier and less prone to errors for you to go into the tags directory and make your edits. This is normally a bit no-no for version control!

So the safer way to do this is to develop your plugin normally inside the wp-content/plugins directory and submit to the trunk as you normally do. Once you’re ready to publish a release, go to a new folder somewhere on your hard drive and checkout your ENTIRE project, trunk, tags, and all. Then you can do your tagging operation locally, e.g. svn copy trunk tags/0.9, and that will give you a new directory. You can update that directory’s readme.txt file and your plugin’s information header, then commit all of your code (trunk and all tags folders).

Hope that helps los dudes.

Writing Custom PHP Snippets for MODx (part VII)

This article and tutorial video takes on how to add custom PHP scripts (known as Snippets) to the MODx content management system. This covers MODx Evolution (version 1.0 and before), but many of these methods and principles are applicable to MODx Revolution (version 2.0) and PHP coding in general.

A video used to be embedded here but the service that it was hosted on has shut down.
Watch Video @ Blip.Tv

Adding a Snippet

MODx newcomers are sometimes confused as to where to upload the PHP files… YOU DON’T UPLOAD IT. You paste it into a database record. You can reference files on the file system, but you don’t have to.

1. To add a Snippet from the MODx (v1) manager go to Elements –> Manage Elements –> Snippets then paste in your PHP code.
2. Be sure to give it a unique name (I recommend avoiding spaces in the name)
3. Give it a category: this will make your Snippet easier to find in the manager.

Recommended Components of a PHP Snippet

This applies to ANY code you write, but for the record, please include the following documentation as comments in your Snippet:
1. SUMMARY: a sentence describing what the Snippet does.
2. INPUT: list any input variables the Snippet can accept. It’s good to note the data type (e.g. integer/string), whether or not they are required, or whether or not they have a default value.
3. OUTPUT: list any special output created by the Snippet. Usually it’ll just be HTML, but it’s good to note any external actions (e.g. whether it updates a database row).
4. EXAMPLE: give an example of how the Snippet should be called.

Sample Comment Block



Coding Suggestions and Rules of Thumb

1. Develop your Interface before you code: that bit about adding comments isn’t just for other users, it can help you determine how you want to be able to interact with your code. Coding to an interface is good way of establishing goals and structure before you even start writing the actual code.
2. Initialize your variables: This cuts down on the possibility of security exploits, bugs, and it makes your code easier to read, e.g.:
$output = '';
$garfield_characters_array = array();

3. Sanitize your input: if you are getting any user entered data (e.g. anything out of the $_POST or $_GET array), sanitize the data using regular expressions and if/then statements. Make SURE you have eliminated any possibility that the data is something other than what your program expects.
4. Test as you Go: PHP doesn’t have a built-in debugger, so don’t go too long without checking to see if your code still “compiles” (technically, you should check to see if it has a valid syntax and if it executes). Checking often will help you track down where you made a mistake.
5. Use Good Variable and Function Names: be descriptive. Don’t become a member of the hated “ASCII Preservation Society”. Besides, if you use unique variable names, it becomes MUCH easier to search for instances of that variable, and you’re less likely to have variable collisions.
6. Group your Code into Units: In a word, use functions that fit on the page. If you can SEE it, you’re less likely to UNDERSTAND IT. Chapters of uninterrupted code are hard to debug and test.
7. Reuse your Code: if there are cases in your code where you’re copying and pasting identical or NEARLY identical parts, then it’s time to relegate that code to its own separate function.
8. Log your Errors: if something goes wrong, let your users know about it. It’s a wonderful thing to use the MODx logging function.
9. DO NOT MIX HTML and PHP! There are a few cases where where this is acceptable, but it is good architectural design to separate your view (i.e. your HTML) from your logic. If you have to edit your PHP code to change div tags or CSS classes, then you probably did something wrong. Instead, use MODx Chunks to format Snippet output; your code will be MUCH cleaner as a result and MUCH easier to maintain.

Including Files from the File System

If you write anything more than simple Snippets, you’ll want to put your PHP file(s) on the file system and reference them from the Snippet stored in the MODx database. You can do this by including a standard include or require statement, e.g.

include($modx->config['base_path'].'assets/snippets/mysnippet/include_me.php');

The standard MODx location would be in your own folder within the /assets/snippets directory.

Things to Remember When Including Files and Using Functions

1. Variable Scope: the $modx super-object and the methods that go along with it will not remain in scope within a funciton; use the global to ensure that the globally scoped $modx variable instance is used inside the function. Compare the two instances of the same API call:
// INSIDE a function
function inside_a_function($chunk_name,$garfield_characters_array)
{
global $modx;
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');
return $output;
}

// Or OUTSIDE a function
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');

2. You can’t return a value directly from an included file: because MODx treats Snippets as functions, it’s considered good form to always return a value, e.g. “return $output;” or “return TRUE;” but this MUST be returned from the original Snippet in the database; if you return output from the included file, you’ll have to return it again from the original database Snippet code. See the video for this quirk in action.
3. Take advantage of the File System: if you are developing stand-alone PHP files, you can use the bash terminal (on Linux or OS X machines) to test the PHP syntax. Simply navigate to the directory where your file is and type:
php -l name_of_your_file.php

A Reference for the VI Text Editor (aka VIM)

If you’ve done any programming at all on the command line (in Linux or OS X, or using Cygwin on Windows), you have probably heard of VI and the other powerhouse command-line editor, eMacs, and the epic battle between them long, long ago in a galaxy far, far away… The goal of this article is to give you a functional overview of the VI text editor and give you a useful reference of its commands. I spent a lot of time putting these notes together, so I hope they’re helpful.

Right off the bat, some purists will snipe me for saying “vi” when I really mean “vim” — the latter being the IMproved version. But pretty much everyone uses vim and they call it vi… most of the time when you type “vi” on the command line, it opens up vim anyway.

Open a file with vi just like with other editors: vi [filename] . If the file doesn’t exist, it will be created. And then you will have entered the realm…

There are 2 Modes: Insert and Command

The insert mode is the “normal” typing mode that you would normally think of when using a word processor. The command mode is when you are typing in commands to operate on the text (in lieu of menus, you’ve got to type in all commands). vi starts in command mode, but if you’ve gone to the edit mode, pressing Esc gets you back into command mode. Entering Insert mode is actually a command. Enter insert mode by pressing i (preceded by the Esc key if necessary): Esc to enter command mode. i to enter Insert mode.

How to Type Commands in Command Mode

The command mode commands are normally in this format: (Optional arguments are given in the brackets)

[count] command [where]

Count is the number of times to run the command (e.g. delete 7 lines), and where is the destination of the action, e.g. save this file as xxx.txt.

I’ve grouped the commands here loosely into groups, some of them corresponding to traditional menu names.

Modes

i – enter insert mode (you can also type ‘a’)

Esc – enter command mode

File (the colon commands, mostly)

:n create a new file (not common).

:e [filename] – Edit (open) a file.

:w – save. :w [filename] acts as “Save As”.

:wq – save and quit. Also ZZ (in caps).

:w [filename] – save as filename.

:set xxx – sets option xxx. See Preferences section below.

:q – quit.

:q! – quit without any prompts (i.e. quit without saving).

Edit

u – undo the last change (or redo it).

U – undo the changes to the current line.

ctrl r – Redo. This redoes whatever you undid.

. – Repeat last command.

x – deletes the character under the cursor (Del).

X – deletes the character before the cursor (Backspace).

d – delete (i.e. cut). Usage is dw, d$, d^, dd. to delete a word, delete till the end of the line delete to the beg. of the line, repeat delete, respectively.

y – yank (i.e. copy).

– clipboard. See “Multiple Buffers” below.

p – paste.

r – replace the character under the cursor (specify count).

/ – Find (searches from the current position towards the end)

? – Find (searches from the current position towards the beginning).

:s[regular expression] – Substitute (find and replace). See below.

View

:set nu – show line numbers (:set nu! to remove)

zc – folds Closed a section of code, delineated by {{{ # code here }}} #

zo – folds Open a section of code, delineated by {{{ # code here }}} #

Format

> – indent highlighted text (like tab)

< – shift tab.

Insert

O – open the line above the line the cursor is on.

o – open the line below the line the cursor is on.

R – enters Replace (overwrite) mode until Esc is pressed to exit.

Navigation

h – move the cursor left

j – move cursor down

k – move the cursor up.

l – move the cursor right.

control F – move forward one screen (i.e. page down)

control B – move back one screen.

H – home window line (top of visible)

L – last window line.

]] – next section/function

[[ – previous section/function

0 – Move to start of line (zero)

$ – move to end of line.

shift g – move to end of document.

gg – move to start of document

ctrl g – returns the current line number.

123 shift g – go to line 123.

Tools

% – when the cursor is on a (,),[,],{, or } this will locate its matching pair.

Window

:split – split screen horizontally

:vsplit – split screen vertically.

ctrl w [up/down/left/right] – jump to new portion of split screen.

ctrl z – move vi to background (recess to the Terminal)

fg – brings the process back to the ForeGround (type this in the shell after you’ve done a “ctrl z”).

Help

:h – help

crtl ] – follow a link in the help file.

:q – closes the help file (it’s actually a separate text file), so you quit it.

Search Commands (Find)

These commands let you search the current file looking for a given string. When you press the ‘/’ or ‘?’ key, the cursor will move to the bottom of the screen, where you will enter the string you wish to search for. Pressing the [RETURN] key will signal the end of the string, and cause the search to take place.

To include a ‘/’ or ‘?’ as part of the search string, you must “escape” any of these characters with the backslash character (\).

==> /search string[RETURN]

This command will let you search forward through the file looking for the string. The search will wrap around to the start of the file.

==> ?search string[RETURN]

This command will let you search backward through the file looking for the string. The search will wrap around to the end of the file.

Press n (n) to move to the next result. Press shift n (N) to move back to the previous.

Mnemonics:

The ‘/’ is a forward slash, and is used to search forward. The ‘?’ is the shifted ‘/’ key, and you can think of the act of shifting as reversing the command direction.

To repeat the search, press ‘/’ or ‘?’ depending on whether you want to search forward or backward for the next occurrence. When the cursor moves to the bottom of the screen, press [RETURN] without entering anything. Vi will use the last search string entered as its target.

Substitute (Find and Replace)

To substitute new for the first old on a line type :s/old/new

To substitute new for all ‘old’s on a line type :s/old/new/g

To substitute phrases between two line #’s type :#,#s/old/new/g

To substitute all occurrences in the file type :%s/old/new/g

To ask for confirmation each time add ‘c’ :%s/old/new/gc

Multiple Buffers ” : Frequently Used Text

Most users just use the general buffer, but you can cut and paste text from/to multiple buffers. There are 36, specified by all letters (a-z) and all digits (0-9). The buffer is specified using the command (the mnemonic here might be to QUOTE something). For example, the command: “mdd uses the buffer m, and the last two characters stand for delete current line. Similarly, text can be pasted in with the p or P command. “mp pastes the contents of buffer m after the current cursor position. For any of the commands used in the next two sections, these buffers can be specified for temporary storage of words or paragraphs.

These buffers remain in memory after vi has closed (for a while, at least… I’m not banking on these buffers being 100% persistent). So you can use them to store frequently used bits of text. For example, you may want to use:

“i to contain the block code for an if statement.

“h to contain basic html tags.

Copy, Cut, and Pasting

(i.e. Yanking, Deleting, and Pasting)

The command commonly used command for cutting is d. This command deletes text from the file. The command is preceded by an optional count and followed by a movement specification. If you double the command by typing dd, it deletes the current line. Here are some combinations of these:

d^ cuts (deletes) from current cursor position to the beginning of the line.

d$ cuts (deletes) from current cursor position to the end of the line.

dw deletes from current cursor position to the end of the word.

3dd deletes three lines from current cursor position downwards.

There is also the y command which operates similarly to the d command which take text from the file without deleting the text.

The commands to paste are p and P. They only differ in the position relative to the cursor where they paste. p pastes the specified or general buffer after the cursor position, while P pastes before the cursor position. Specifying count before the paste command pastes text the specified number of times.

Keep in mind that the targeting of the pasting actions isn’t where you’d expect from working with traditional word processors.

Execute External Commands

Type :! followed by an external command.

:! perl -d % launches the current (perl) script in debugging mode (very useful!).
:! php -l % if you’re editing a php file, this checks syntax.

Highlighting Text

v – enters visual mode so you can highlight a visual block. You can highlight entire lines AND columns. Very cool.

To highlight several lines: ctrl v, then hold shift and use the arrow keys and the Home and End keys as you would do normally in commercial word processor (or the j,k,l… equivalents). E.g., pressing d after highlighting a block would delete it (cut it).

Shift g moves to the end of the document.

Alternatively, with most terminals you can use the mouse to highlight a block of text, then move the cursor to where you would like to paste it. A right-click will paste the text. However, this method is a bit awkward because of the keyboard/mouse/keyboard interaction.

Setting Preferences using :set (Pimping Your Ride)

You can set a number of preferences in vi including text and highlight color. Many of these options can be set using :set. Notice than anything you can set, you can unset by using the same command followed by ! – the exclamation point is the universal program code for NOT.

:set ic – ignore case (for searches)

:set hls– sets highlighting for a search

:set is – include search

:set nohlsearch – remove highlighting (or use :set hls!)

:set ai – sets autoindent

:set nu – adds line numbers. (:set nu! to remove)

Edit your ~/.vimrc file to add preferences to this file to make them permanent. E.g. I have the following in my ~/.vimrc file:

highlight Comment ctermfg=lightblue
highlight Search ctermfg=0 ctermbg=3*
set tabstop=4

Other Useful Functions

To push a vi window (or any window, really, to the background) press ctrl z. To bring it back, press fg (for ForeGround). There is fg1, fg2, fg3, etc.

Conclusion

Well, there’s my reference for you fine folks. I may grow some more hair on my chest if I ever do the counterpart for eMacs… but I’m not holding my breath. As of Sunday, this article represents the knowledge gleaned from 2 years spent editing scripts on the command-line. In parting, I’ll share one little tidbit of wisdom: don’t worry too much about the navigation shortcuts: although some shells don’t support the standard arrow keys and Page-Up/Page-Down key bindings, most of them do. Whew!

Please feel free to add corrections or additions to the comments!

10 Great OS X Applications for the Web Developer

One of the things I think of every single working day is how great a platform OS X is for software development. Now, take that with a grain of salt… I do development in a LAMP dev shop running Linux, Apache, MySQL and Perl/PHP, but we’re running some enormous sites (LowFares.com, IdentityTheft.com, and Low.com). All of those technologies are open-source, and (in my opinion) very well suited for serious commercial sites. Java is fine if you need to send a man to the moon, but it you just need to say “Hello World!”, you’re still might be dealing with a rocket launch…

Peanut Gallery Java Pot-Shots

.NET isn’t any better… every .NET shop I’ve dealt with has had horrible down-times and massive release delays… but I digress…

Why is OS X Awesome for Software Development?

  1. Exposé — this feature saves me 30 to 45 minutes per day (yes, I’ve timed it). It’s unbelievable how much time you can save if you can quickly get between documents and apps.
  2. The BSD Subsystem — if you’re working with Linux/PHP/Perl/MySQL, it saves so much time to have OS X’s Terminal right there with a Unix variant under its hood. No need to emulate with Cygwin or go remote with Putty. You can test your Apache config or database queries without ever having to connect to the network.
  3. My Mac Runs Windows! — I can test my web pages in all major browsers by flipping between OS X and Parallels Desktop running Windows, or by using VirtualBox.
  4. It’s Not Windows — ha ha… I had to slip that one in. Sorry if you’re suffering through XP. I mean Vista. I mean the NT kernel.

Top 10 Applications for Software Developers on OS X

Ok, on to the main event. Here are ten great applications for a software developer working in OS X. These are the applications that have found an integral place in my workflow. Not all of them are free, but I have tried to list a free alternative when appropriate. I’m not recommending you get ALL of these, but depending on what exactly you’re doing, you might want to try out a handful of them.

iTerm: A Better Terminal

1. iTerm (Free)

Link – iTerm

This is to the command line what Firefox is to browsers: if the Terminal is IE, iTerm is like Firefox. It is simply a better Terminal. It allows tabs and bookmarks for those of you who log into multiple servers.

TextMate: a powerful interface and editor2. TextMate ($57)

Link –TextMate

I do like Smultron a lot (it’s free), but TextMate’s interface is preferable to me. It’s similar to a full-featured IDE such as Eclipse (which is also free) because it gives you a full folder-structure view in its document drawer (something that Smultron or TextWranger do not).

One thing – unlike Eclipse, TextMate is lightweight and fast without ump-teen Preference pages. If you need an IDE, give NetBeans (free) a try.

Transmit: a Powerful FTP/SFTP client with a great interface3. Transmit ($30)

Link –Transmit

Although there are free FTP clients out there, Transmit has one of the best interfaces because it incorporates Mac OS X’s column view. To be fair, I have had some problems connecting to certain servers when using Transmit, but I don’t know enough of the firewall internals to know why one client performed better than another.

If you prefer a free alternative, my recommendation is Cyberduck (free).

Sequel Pro is the sequel to CocoaMySQL4. Sequel Pro (Free)

Link –Sequel Pro (Free)

There are only a couple of choices when it comes to GUI MySQL interfaces for OS X, the other big one being Navicat (they have a lite version that’s free). The other popular choice for a long time was CocoaMySQL, which is still available for 10.4 users, but development on it has been abandoned and the project has moved over to Sequel Pro (the sequel… get it?) Sequel Pro offers an improved interface for 10.5 users (I prefer it to Navicat).

OmniGraffle: graphing, flowcharts, and designs5. Omnigraffle (Bundled with OS X, or $100, or $200 – Pro)

Link – OmniGraffle

Imagine Microsoft Visio, but clean and not bloated and well… not Microsoft. If you have to diagram databases or put together product requirements for documentation, this is a beautiful little product that may have come bundled with your Mac. The Standard version can almost get you through the medium and large projects. I haven’t seen anything on the Mac that comes close to what this application offers, and even though I get the feeling that the high price tag is getting validated by riding Visio’s bandwagon, I still think this is a good bit of software.

6. PhotoDrop (Free)

Link – PhotoDrop

This is a very simple app that lets you create droplets for bulk image processing. Each droplet can do things like convert images between formats, perform scaling and cropping, even watermarking. If you are doing web development, this is just a simple (and much cheaper) alternative to running Photoshop’s Save for Web feature over and over and over again. Very, very handy.

unArchiver: never type a weird command-line un-tar statement again.7. The Unarchiver (Free)

Link – The Unarchiver

This is handy if you’re frequently dealing with Zip, Tar, GZip, BZip2, Rar, 7-zip, LhA, and StuffIt files. Yes, you can handle many of these on the command line, but if you’d rather deal with a GUI, this tool is handy.

8. Nvu (Free)

Link – Nvu

This is a complete Web Authoring System for Linux, Windows and OS X. It’s like a free version of Dreamweaver (which maybe you’ve already outgrown?).

It has good support for style sheets and a Javascript console, but one irk is that the tabs that show multiple open documents seem to disappear if you are viewing the HTML source for the document (instead of the “Normal” WYSIWYG view). If you’re beyond the integrated WYSIWYG type of thing, have a good look at Eclipse (Free)… it’s a big framework that does a lot of things, but a number of web developers I know use it for its convenient browsing and previewing capabilities. Eclipse also integrates with versioning software (like SVN), but because it’s heavy-hitting, I only recommend it for more mature users. NetBeans looks to be a lighter alternative to Eclipse, but I haven’t tried it myself.

9. Seashore (Free)

Link – Seashore

This is a lightweight photo-editing application. It’s got all the things in Photoshop that I use frequently (layers, brushes, and exporting for web). It’s got some handy keyboard short-cuts, but it’s missing others.

SuperDuper: Elegant and Powerful Backups10. SuperDuper! (Shareware, $28)

Link – SuperDuper!

This is a popular backup utility. If you’re serious about doing development work, you know there is a lot of effort put into maintaining your valuable code and prior versions of it. You can use SuperDuper to create bootable clones of a drive, too. Hot stuff.

You can use SuperDuper! for free (forever), but the advanced features are available for a $28 fee.


Honorable Mention: Fluid (Free)

I mention this little app because I’ve found it extremely handy over the past couple days. If you compile a site into its own app, you can take advantage of the built-in Apple-tab shortcut to get to it. Another really helpful thing about working within the application-switching workflow is that you can assign the application(s) its own icon. That’s REALLY helpful when you’re working with a dev and a production version of a site… honestly, those simple little things can prevent disaster.

But the real reason I was compelled to mention Fluid is its inspector. It breaks a page down into the html tags, images, and style sheets ridiculously well. In my opinion, the layout of this program is sickly good… IMHO it’s better than the revered debugging plugin Firebug for Firefox. Wow. Yes, really. I’ve never had an easier time tracking down problematic HTML or a goofed up CSS declaration. However, the Fluid-compiled web site seems to have some weird behavior with its caching… you know the drill: make your edits, clear the cache, refresh the page. But sometimes the Fluid version doesn’t refresh correctly. I don’t know if this is something I can configure or if its an artifact of compilation, but I really hope it’s the former. The DOM inspector is just too slick to overlook. For more information, check out Brian’s post about Fluid.

Summary

I hope you’ve benefited from my sharing of this short list. I don’t recommend that you rush out to get all of these programs: some of them may be more relevant than others. If you think one looks interesting or practical, give it a try and see if you like it. Feel free to post your own suggestions about helpful OS X applications for software and web development.

Feature image credit: Guillermo Esteves

Introduction to Bash Scripting

Here’s a great tutorial for bash scripting: http://www.linuxconfig.org/Bash_scripting_Tutorial

Linux and OS X: Harness the Power of Bash
Linux and OS X: Harness the Power of Bash

If you’re doing any work with Linux or OS X computers, knowing even a little bit of bash can save you a whole lot of work. You can write automated backup scripts, you can scan for faulty permissions… the list is endless. You’ll end up building a toolbox of common scripts that you will use in multiple places.

Only one thing wasn’t given much attention on that page, so I thought I’d point it out:

for next Loop

Usually, your programming syntax is cleaner if you avoid the for next construct and stick to the for each construct instead, however, with bash scripting you often need to work with that crazy little numerical iterator for changing things like file names (e.g. backup1, backup2, …). So you should get familiar with the seq command. It creates an array, going either forwards or backwards, and then bash’s for next loop iterates over that array.

Here’s the seq syntax:

seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST

And here’s how you might iterate backwards over an array:

LIST=`seq $NUMBER_OF_ROLLBACK_FILES_TO_PRESERVE -1 1`;
for I in $LIST; do
echo "I is $I";
done

Now get over to http://www.linuxconfig.org/Bash_scripting_Tutorial and start learning.