Quick Command Line Method to Get Memcached Stats

I had to look for a while to figure this out:

echo stats | nc 127.0.0.1 11211

This assumes the memcached instance is running on a local instance with the standard port. This will output a bunch of statistics about the machine. The one to watch is “evictions,” which represent items getting overwritten before they naturally expired. This would indicate items being cached too long or the server running out of memory.

Is PHP here to stay?

As a LAMP developer, I am starting to question the long term viability of PHP. PHP was born during an era when knowing HTML was a valid and valuable resume bullet. Because of this, most of the “advanced” aspects of PHP — which relate to the OOP functionality — were introduced only after PHP 4/5, and weakly at that. Additionally, new languages have since become popularized that show the weakness of PHP. Don’t get me wrong, I am very supportive of PHP. I just believe that it’s important that people understand both the strengths and weaknesses of the tools they use.  There are two main points I want to cover:

  1. PHP thread support is weak
  2. PHP OOP = Broken

The second point is rather technical, but it closely relates to another strength and weakness of PHP: it is loosely typed. More on that later.

Thread Support is Weak

True threading support in PHP does not exist. The closest thing is the pcntl_fork method, which copies the current process, rather than create a thread. This means asynchronous processing within a single process is not supported. Threading is useful in event-driven architectures (common in JavaScript) or when doing blocking operations such as network calls.

Because the forked process is a clone of the original, it shares all of the original resources, including database and file resources. This means that the forked process must be self-aware of whether it is a child or not, and must be careful not to modify or close these resources. This encourages spaghetti code that contains large logic forks (“if I am not a clone, else…”). Because of this, forking is messy and error prone. This gets further complicated when PHP is executed by Apache in a web environment. In fact, the PHP manual advises avoiding forking with web servers:

Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

Not to mention the method is incredibly C-like in that it is very “raw” (unlike other native PHP methods/classes). This increases the barrier to entry significantly, which ultimately serves to have the feature ignored by most shops.

Why is all of this important? Well, at most companies, one language is selected for all in-house development. This is because cross training and hiring is simplified if everybody speaks the same language. There are a few common tasks that are unnecessarily difficult to do in PHP:

  • Asynchronous work — handing off work such as connecting to a remote server to a child and wait for a response
  • Manage thread pools — this sort of work requires significant “by-hand” management of any processes spawned by the parent via pcntl_fork

The threading issue is only a pain point that impacts processes that need to become parallelized. It is a pain most big shops live with, or, alternatively, introduce other languages to help solve.

PHP OOP = Broken

Because of the loosely typed nature of PHP, true, well-formed object oriented programming is broken. I know that for many PHP programmers, “Object Oriented” means putting together classes and reusing code as objects. However, that is truly, sincerely, only a portion of the point of OOP. Some of the most powerful aspects of OOP are lost in PHP’s implementation of the concept. Don’t get me wrong: these decisions were probably the right fit for the niche PHP was filling, but I don’t believe most PHP programmers are fully aware of what they are missing.

While the language, thankfully, has interfaces and abstract classes, they are woefully underused. This is, in part, due to to the developer community being largely self-taught. This creates a misconception about the nature of OOP, which ultimately leads to the devaluation of the most important feature of OOP: interfaces.

I can go into why they are so important in another article, but the point is: without interfaces, true polymorphic code is impossible. Or, rather, extremely susceptible to spaghetti code and fatal errors.

In other languages (Java), code might look like this:

interface Animal { void makeSound(); }
void farm(Animal cat, Animal dog, Animal parrot) {
  cat.makeSound();
  dog.makeSound();
  // Note: Parrot class *DOES* have a method called moveAround()
  parrot.moveAround(); // ERROR!

The interface in this example defines a uniform way to access a class through a standardized API (thus the name, application programming interface). In a strongly typed language where all variables must have a type, the cat variable is defined as an implementation of Animal. This enforces and allows the method call makeSound(). If cat has a meow() and dog has a woof() method, they can not be called here without a compiler error. This is because in this function call, the parrot variable is defined as being an instance of Animal (versus being a Dog, Cat, or Parrot). As such, only Animal methods work here.

More importantly, because the compiler does this type checking, any invalid calls, such as the last one, would error and never compile. Even if the Parrot class has a moveAround() method, it can not be called in the code above. This is an extremely important aspect of OOP since, as a definer of the Animal class, I want to make it very specific how Animals should be treated (you can only makeSound!). If a programmer tries to do something to an Animal that I haven’t defined, they get an error. If they wanted to make that last line work, they would need to use object typecasting:

void farm(Animal cat, Animal dog, Animal parrot) {
  ...
  ((Parrot) parrot).moveAround();

Or by changing the function definition:

void farm(Animal cat, Animal dog, Parrot parrot) {
  ...
  parrot.moveAround();

But note that in this case, the user had to make an explicit choice to stop using Animal’s interface. Yes, parrot is still an Animal, but it doesn’t have to be. This, in short, helps prevent spaghetti code because it forces the developers to think about whether or not they want to deviate from a particular interface. Realistically, if presented with these alternatives, a Java programmer would probably use other types of abstraction techniques (e.g., dependency injection)  to keep this method from needing to be used. However, this example was necessary to illustrate how things are done in PHP.

So how would this look in PHP? Why isn’t this the same there? Well, take a look at the following code that, unlike the Java example, works perfectly fine and raises no red flags.

interface Animal { function makeSound(); }
function farm(Animal $cat, Animal $dog, Animal $parrot) {
  $cat.makeSound();
  $dog.makeSound();
  $parrot.moveAround(); // WORKS FINE 
}

This code works great. We have three arguments all forced to use the Animal interface. Great. As a casual observer, there is really, truly, nothing wrong with this code. It’s a little strange, but if it’s commonly known that Birds can moveAround(), there is no problem. In fact, in most PHP shops, I will bet money that type hinting is NOT used. This will further illustrate how bad the spaghetti is about to get (read on).

Now imagine in six months if we decide we wanted to group up this code so that it uses a single array/collection as an argument. This is where things would look like traditional polymorphic code. I mentioned spaghetti above. Let me show you why:

interface Animal { function makeSound(); }
function farm(array $animals) { // note, we can't guarantee what's inside of this array
  foreach($animals as $animal) {
    if($animal instanceof Parrot) { // or maybe a method_exists() call?
      $animal.moveAround(); // SPAGHETTI
    }
    else {
      $animal.makeSound(); // Hope for no fatal errors!
    }
  }
}

Wow, look at what we just did. A harmless piece of code in PHP six months ago completely breaks when you try to refactor it to use a fairly typical design pattern. More importantly, unless I put in even MORE code to do type checking, there’s a chance that the makeSound() line will actually die in a fatal error if, for example, a string is passed in as an element of the argument array! See example without Parrots:

interface Animal { function makeSound(); }
function farm(Array $animals) { // note, we can't guarantee what's inside of this array
  foreach($animals as $animal) {
    $animal.makeSound(); // Hope for no fatal errors!?
  }
}

PHP is extremely flexible when it comes to hacking out a page, but when it comes to OOP, it’s about as brittle as you get. Refactoring is painful and error prone, and elegant design patterns like the ones you might see in a message-passing language such as Objective-C, Scala, or Erlang don’t work. Remember that by using functions such as method_exists() and is_object(), I can emulate the desired behavior; however, the extra code means more places for bugs and less time spent making the program do what you want it to do. The point is that the OOP constructs in PHP don’t fully work. As a result, certain very important aspects of OOP don’t translate very well to PHP.

Some people may still cling on to the notion that “ultimately, you can still do it, it just requires more code!” But I argue that preventing “more code” is the exact reason why OOP was invented. By writing more boiler plate error checking code, we are wasting time. The issue is exacerbated by the fact that the error checking code isn’t required, unlike say, if you were throwing exceptions. It isn’t immediately obvious in that last example that you need to do error checking for is_object() on the $animal variable. It’s these types of oversights that really damage PHP as the code base gets larger.

Conclusion

What I’m realizing is that PHP isn’t meant to scale. Yes, it can take a lot of web traffic, but that’s not what I mean. I’m talking about scaling in the sense of growing team size and code base. The design of the language promotes coding paradigms that ultimately damage the code base. This is because PHP makes it harder use good OOP practices on legacy code. To illustrate:

  • PHP became popular because it is easy to hack things out, even if that something required doing it the “wrong” way. These problems come back and bite you when the code base grows.
  • PHP can’t support a large development team as effectively because its weak typing allows for sidestepping certain core OOP principles (see above)
  • PHP  allows for invisible future-bugs (see above) to be inserted without any immediate cause for alarm
  • As applications get complex and require threading or distributing of processes, PHP fails to keep up (so other languages get used)
  • Because PHP does not use dynamic dispatching (message passing), calling a method can cause runtime FATAL ERRORS (unacceptable and very hard to debug!)

All of this makes me rethink the popularity of PHP. There are some new languages, still in their infancy, that pose a threat to PHP’s current dominance. I believe that in the next few years, as today’s systems become “legacy,” today’s newcomers will finally be production ready. At that point, we might see companies adopt the newer languages, which will support more modern programming paradigms. We are seeing this today with Ruby, for example.

Of course, I could be wrong. I once told people that PHP was “C of the web.” It’s possible it’s here to stay forever, despite all of its flaws. And, for the record: I do not believe Python or Ruby will be the language that will overtake PHP, but that’s for another post.

I just want everybody to know that I am a PHP developer, so I speak from experience. We should recognize that technology changes and evolves, and it is important that we constantly update our skill to ensure they don’t become obsolete. I’m just pointing out that perhaps PHP isn’t as timeless as C (or, possibly, Java).

Lastly, I will plug my personal belief that being “religious” about a language because it is “the best” is short sighted. New languages are born, literally, every week. It’s only a matter of time before a language comes along that does what your language does more elegantly, faster, and with less code.

Only time will tell. 🙂

YSlow – Firefox Add-on for Developers

logo_32x32I just came across a really neat tool released by Yahoo called YSlow.

The basic idea is simple: it is a Firefox add-on that can be used to analyze pages you view. This analysis gives you important insight into why a particular page loads slow.

If you are a web developer in charge of the front end components, I urge you to check this tool out.

perfview

How the iPhone Will Save Web Standards

Today, Apple has announced the beta release of Safari for Windows – the browser that will be shipped with every iPhone.

safari

This is great on multiple levels:

  1. Developers can finally run tests against the Safari browser without having a Mac (usually these tests simply didn’t happen). This was the reason many sites broke on Macs.
  2. Safari has a strong track record from Mac enthusiasts, which is a mostly separate crowd from Firefox enthusiasts. Thus, this may help further increase adoption of non-IE browsers.
  3. Applications can be tested against the iPhone without an actual iPhone in hand.

That last point is crucial. Right now, everything targets IE, and this is a pain for web development because IE bastardized web standards such as HTML and JavaScript. This meant anything you programmed had a chance to break in IE even if it worked in every other browser on the planet. 

The iPhone may be the best thing to have happened to the Internet since Firefox was born.

If the iPhone becomes the new target platform, standards become truly relevant. Why? Because for the first time in history, hordes of regular Joe consumers will have web access in the palm of their hand, and no company wants their website to completely break when viewed through the iPhone. This is especially true as more and more people begin to consume information strictly through their handheld devices and stop visiting web sites that don’t work on their phones. As a personal example, even though I read lots of news sources when on a desktop, on my Blackberry, I only read a select few sources that are built to handle mobile browsers.

The point is: web publishers can no longer choose to target IE. And as many analysts predict, with or without Apple, the mobile web will match or over take desktop web usage in the near future. Just take a look over at Japan to see what I mean.

So as a developer, I would like to thank the iPhone for making my life better. 🙂

Using IE7? Test in IE6 with a Stand Alone Browser

This is old news to some of you. In fact, I’ve known about this for many months now.

With the introduction of IE7, testing for IE6 compatibility issues has become a real pain. I would know — I encountered them when redesigning this site.

Anyway, there is a stand alone IE6 download at evolt.org which works flawlessly. Simply download the ie6eolas zip file, extract it, and run iexplorer.exe. It’s great.

Man Cheats on Aids Wife, Aid Bows Out with Dignity

I just came across an article today about a Mayor who had an affair with his campaign managers wife.

After his wife told him about the affair, Tourk approached the mayor about it, then resigned… “It has been an honor and a privilege to serve the Newsom campaigns and the city of San Francisco and its residents,” Tourk said in a news release…

Newsom, who is seeking a second four-year term in November, said in the statement that he accepted Tourk’s resignation “with great sadness,” adding that he was “an extraordinary leader of our campaigns and a tireless public servant.”

Now that’s professionalism. A moment ago, I blogged about the value of private discussions, which, clearly, is what happened here. Yelling, crying, shouting, who knows? But you know what? The public never will.

Imagine if that was some Web 2.0 hot-shot CEO. You can already imagine how he might have handled the situation. Professionalism goes a long way, no matter who’s in the wrong. Please, if you ever become a well-known Internet blogger, keep your dirty laundry and corporate bashing to yourself.

That is, if you don’t want to look like a 16 year old.

LetsTorrent.com – An Experiment in Google Coop

Last night, I decided to give Google Coop a try. I created LetsTorrent.com.

It’s best features are:

  • I didn’t just pile on every torrent site I could find. I filtered out tons. I only chose ones that described the torrent files, didn’t have popups, didn’t require registration, and didn’t link to content on other torrent sites.
  • No direct links to torrent files so you don’t have to try to decipher gibberish like S03ZSub6_-AAA-325581-[zan].tar.torrent. I had to omit some popular torrent sites due to a lack of having details pages in order to stick to this philosophy. I hope the trade off is worth it.
  • It searches over 70 torrent sites in one shot. And the results are highly relevant.
  • No mirror bullshit. Since I hand-screened every site in the engine, I made sure no two sites stole content from each other. The goal is to ensure you don’t get the same file linked from 10 different sites as 10 different results. You get one.
  • It uses the Google Engine, thus it’s much faster than using the search engine on a torrent site.

The site uses some relatively simple event handler JavaScript. I plan on writing about it in my next entry when I unveil the other, more JavaScript intensive experiment. Stay tuned. 🙂

LetsTorrent.com. I know I’ve made something good when my girlfriend says she wants to use it. 

Enjoy. 🙂

P.S. I posted this earlier, but the domain wasn’t fully registered yet. It should be now.

.htaccess, Notepad, and Windows

When trying to name a file with an “invalid” name, notepad can come to your rescue! Ever try to create a .htaccess file on Windows? You’ll get the following error message:

You must type in a filename

Windows doesn’t like files with only a suffix. However, an .htaccess file is a special, and an often necessary component in many web applications. If you happen to be running a web server on your Windows box, this presents a problem.

You can get around this problem by using notepad. Simply open notepad and save the file. During the save dialog type do the following:

When you hit “Save,” the file will appear and everything will be dandy.

The Best PHP Book Out There

Advanced PHP Programming I’ve read quite a few PHP books, and most of them suck. Many of them contain the same or very similar material recycled with new examples. Only one stands out in my mind as truly exceptional: Advanced PHP Programming. I am willing to bet this is the best book out there for novice to advanced PHP developers. It is not the best beginner book as it has some advanced topics (as the title suggests), but the material it covers is seldom mentioned in any detail in other books.

The book is an excellent resource for novice programmers hoping to become “experts” in the field. Granted, the coverage in the book is a little superficial in some places, but it serves as an excellent introduction to advanced concepts. These concepts played a major role in my understanding of scaling PHP applications.

After developing PHP for nearly a year by the time I had read the book, I remember thinking how much time the book would have saved me had I read it earlier. Many of the lessons the book mentions are things novice programmers learn from trial and error or from tons of Googling.

The book most notably covers some very common problems a PHP developer unexpectedly faces at some point in their career:

  • Session management, especially when integrated with a database back end
  • Common security misconceptions
  • A real database abstraction layer layer (warning: difficult example for beginners)

It also covers some of the new features of PHP 5, which is still foreign and underused by many:

  • Exception handling
  • Object oriented development (with some best-practices included!)

Personally, and this is strictly personal, I feel very much more confident in a developer’s ability when I see her/she is able to write clean, object oriented code that uses exception handling. This is very common in C++ or Java, but is relatively uncommon in PHP. In general, these are good programming practices.

It’s been a few years since I first picked up that book, and even today, sometimes I skim through it and think, “Oh, I forgot about that!” The book was the single greatest investment I ever made in my PHP skills. I’ve recommended this book to every novice PHP developer I’ve ever met.

If you know PHP, but want to know PHP, buy this book. It’s the gateway drug into an advanced PHP programming high.

I find my analogy funny.

Why is Software Development So Hard?

Why is software development so hard? That was the topic of a Slashdot article that was featured today. In short, the article was asking why, after all of the collective experience in software development, is it still notoriously difficult to get quality software out on time, without bugs, and under budget.

On one hand, it’s obvious that software development is still a relatively young “science,” as it has not been around for even half a century. Despite this, the article had an interesting point. Why is it that no matter how many times companies produce new software, they inevitably fall victim to delays. Just look at Vista, the next version of Windows that has been delayed over three years and shed large portions of its original specifications. Less features, more money thrown at the problem, and yet still late by three years? How, you ask?

I am not linking you to the actual article because it isn’t nearly as interesting as this comment I read in response to the question. A clever reader wrote in response:

Why is conducting an orchestra so hard?

Some might read that and think it was a joke. But the next reply put it into context.

It isn’t. Haven’t you seen them, all they do it wave their hands around and look silly. That’s the point. Everyone thinks it’s a breeze when it isn’t, so everyone underestimates everything.

Of course, my sharper readers would notice that these answers don’t actually answer the question. In fact, all they do is dismiss the question by saying, “because it is harder than it looks.” This brings up a very important lesson that seems to elude many companies (thankfully not mine) when it comes to IT project managing. You can’t expect a masterpiece without the talent, knowledge, and experience. Another reader wrote:

A good orchestra conductor who is in front of a bunch of rank beginner inexperienced musicians will not be able to make very good sounding music. You get what you pay for.

Amen.