ImageMagick + Gimp + PNG Offset Trouble Vim Uppercase & Lowercase
Aug 20

I have been developing PHP applications professionally for over 7 years. About a year ago, I decided to try developing some Ruby on Rails applications. My main Ruby on Rails projects have included an e-commerce site QuietHeadphones.com and an online application for synchronizing medical records with USB thumb drives. Of course, I have also worked with the Ruby on Rails blogging engine Mephisto which is what runs this website. So while I have worked with PHP for more time than I have worked with Ruby on Rails, I have worked with Ruby on Rails long enough to have noticed some significant differences between the two languages. My comparison is going to focus on the language differences between PHP and Ruby and not as much on the Rails framework.

There are rather significant syntactical differences between PHP and Ruby. For example PHP requires semicolons at the end of lines and generally requires curly brackets to enclose blocks of code. Ruby, on the other hand, uses newline characters to denote the end of a line of code and many code constructs such as function definitions, and various loops are ended with the word “end” rather than being surrounded by curly braces. Below is an example of PHP vs Ruby syntax.

PHP Function

function say_hello($name) {
  $out = "Hello $name";
  return $out;
}
Ruby Function

def say_hello(name)
  out = "Hello ${name}"
  return out
end

In Ruby, you don’t have to specify the return line as the return value of the last evaluated line is returned automatically. There are other differences in syntax between PHP and Ruby and, in general, Ruby is more concise yet it is not cryptic. Another general note about PHP is that PHP has a very large number of “built-in” functions – many more than Ruby. The Rails framework adds some nice helper methods for formatting dates, numbers, currency, and the like. PHP, however, has a vast library of functions that can do almost anything you will need. The naming of the PHP functions and the order of the parameters they take are somewhat inconsistent, but the functions are there making PHP an amazingly complete tool set for web application development. An example of the naming inconsistency is evident in function names such as strpos() vs str_replace(). Sometimes an underscore is used to separate words and other times it’s not. While that can be annoying, it’s something you can memorize in time and it’s not a huge deal. What really matters to me is what can PHP do that Ruby can’t and vice versa.

PHP5 was first released over three years ago, July 13, 2007. Frustratingly, and for various compatibility reasons, PHP5 is just now beginning to be an available choice on shared hosting accounts. Nevertheless, my comparison is between PHP5 and Ruby. Both PHP5 and Ruby have object oriented features albeit, Ruby is more sophisticated in terms of OO constructs. But I wanted to know what the real difference is between the languages. When I begin development of my next web application, what will I notice in terms of the differences between the languages.

The Similarities Between PHP and Ruby

Before getting started, I know that PHP and Ruby have very significant syntactic differences and different people may prefer one over the other. So it may be harder to implement certain features in one language over the other. Nevertheless both languages can do almost the same things. Both languages have try/catch/throw style exception handling. Exceptions are new to PHP5 as PHP4 does not have them. Both languages can be used in an object oriented way. Ruby has more powerful object oriented features but most developers probably won’t notice a difference in a normal web application. Both languages have additional functionality that can be added through libraries. In general, when developing web applications, I have not yet run into a time when I was working with one language and hit a road block where the language I was using was not capable of expressing the functionality I needed. Sometimes things are easier in one language versus the other but both PHP and Ruby have been able to “do” the same things.

About Frameworks

You can’t talk about Ruby for web development without mentioning Rails. Rails is fantastic and makes developing web applications much easier due to all of the built-in functionality. My favorite aspect of Rails is the ActiveRecord functionality. Often times, many of the objects in my applications are virtually empty except for inheriting from ActiveRecord. Validation is a breeze with Rails and is usually one line such as:

validates_presence_of :attribte_name

The built-in error handling with error_messages_for is very helpful. If you need more flexibility with the display of error messages, there are plugins to available for that. The ability to turn email sending on and off for testing is extremely nice. Having different configuration files for live, testing, and development environments is great.

PHP has over 40 different frameworks available. I’ve spent a significant amount of time studying PHP frameworks. The most popular ones appear to by CakePHP and Symfony. Both of these frameworks are essentially Rails clones. I think Symfony is the largest, and most comprehensive of the two. My favorite PHP Framework, howevever, is CodeIgniter. It is a Model-View-Controller style framework and has a strong Rails feel to it, but it is much lighter weight. CodeIgniter has no code generators like Rails has. It does have an ActiveRecord style Database class but it is not as powerful as the ActiveRecord in Rails. It is, however, quite nice and very helpful – much better than nothing. CodeIgniter, as far as I know, does not have anything comparable to Migrations in Rails.

PHP Does Not Have Formal Namespaces

PHP does not officially support namespaces and Ruby does. So organizing your code in a PHP application is something that’s left to the developer to figure out. PHP5 has the ability to autoload classess that are undefined. It is a very useful function and one that I have used to organize my code into name spaces. I essentially name classes with underscores separating directory names. Here is my autoload function that replaces underscores with slashes to create a path to the class files that I am using.

define("PROJECT", "/path/to/project/classes/");
define("LIBRARY", "/path/to/my/main/php5/library/classes/");

function __autoload($className) {
  $fileName = str_replace("_", DIRECTORY_SEPARATOR, $className) . ".php";
  if(preg_match("/^ProjectName_/", $className)) {
     include_once(PROJECT . $fileName);
  }
  else {
    include_once(LIBRARY . $fileName);
  }
}

I have a bunch of classes that I continually reuse in my PHP applications. The path to the root directory of my library is stored in the LIBRARY constant. Any classes I write that either extend my core library or are specific to the project I am working on get stored in the location specified by the PROJECT constant. This has been a system that works really well for me and is a good workaround for PHP not having namespaces. So PHP not having formal namespaces has not really hindered my development efforts.

Documentation

PHP kills Ruby and Rails when it comes to ease of finding, reading, and even generating documentation. The PHP website has wonderful, helpful, searchable documentation. The Rails Documentation is comprehensive but much harder to navigate and has far fewer code examples. PHPDocumentor also produces much better looking documentation that is easier to navigate than RDoc does.

Hosting Ruby (on Rails) Is Painful And Expensive

All the Ruby applications I have developed to date have used the Rails framework. So this is a comparison between hosting a PHP Application and a Ruby on Rails application. PHP has several good MVC style frameworks. My favorite is CodeIgniter and I’ll be posting an article about it soon. Using a framework or not, PHP is extremely easy to host. Locate virtually any hosting company, sign up for an account and start dropping your files on the server. I can’t say the same for Ruby on Rails.

I started off with a DreamHost account but performance and reliability were miserable. I ended up switching to a virtual dedicated server at Rimu Hosting and have been extremely please with their service. I’m running Apache 2.0 + Mongrel + ISPConfig and it’s working out nicely. But every time I want to deploy a new application I have to…

  • Set up a mongrel cluster
  • Configure 2 or three ports for the mongrel cluster
  • Create a map file for my random load balancer
  • Set up a way to restart the cluster if the server reboots
  • Configure Apache to forward requests to the mongrel cluster
  • Configure capistrano to deploy the application.

Fortunately capistrano handles all of the annoying tedium associated with deploying the application and restarting the server. So once capistrano is setup and working, future deployments are a breeze. Also worth noting, this assumes you have your source code in Subversion. So you have to make sure that Subversion is set up and accessible over the internet to the deployment server as well as your development machine. It is good practice to have you source code in version control and you should be doing this whether the project is PHP or Ruby. If you are not using subversion and, therefore, not using capistrano, deploy a rails application is very time consuming and frustrating. Lastly, you need ssh access to your deployment server if you are going to be using Ruby on Rails whereas PHP can be deployed entirely over FTP.

To have a reasonable and reliable hosting environment for Ruby on Rails applications, you should have a virtual private server (VPS) or a dedicated server. So that will cost you at least $50 per month. You can host multiple Rails applications on the same VPS but the RAM requirements for running the mongrel clusters will quickly catch up to you. While you could host well over 50 PHP sites running on your VPS you will only be able to have a handful of Rails applications.

Conclusion

I suspect very few people will argue that PHP is a more elegant language or is more powerful than Ruby. Frankly, Ruby is probably may favorite language that I have ever worked with and I have worked with Classic ASP, ASP.NET, VB.NET, C#, Java, and Perl all rather extensively over the years. Ruby is both highly expressive and concise which is rare and refreshing.

Rails is a very comprehensive and effective web development Framework and there’s nothing exactly like it in PHP. You get a huge amount of functionality for free. Developing in Ruby on Rails is also a very fast process because Ruby is a very concise language requiring much less typing than any other language I’ve worked with. CodeIgniter is a really nice PHP framework. It will give you a great boost when developing your next PHP application.

The hosting and deployment struggles with Ruby on Rails is a major sticking point for me though. As the owner of a web development company many of our smaller clients do not have the budget for their own VPS account and even if they did, we don’t have the staff to manage a large number of VPS accounts or dedicated servers. Keeping the security updates current, managing any issues that may occur with email, and all the other headaches that go along with managing your own VPS or Dedicated server is more than we care to take on for the relatively small, practical dfference between PHP and Ruby. For large projects, it may be worth the trouble, but for small to medium sized projects, PHP is much easier to deploy, less expensive to host, and the language is capable of taking on everything those types of sites require. For our projects, development time with PHP is not noticeably longer than with Ruby on Rails. Ruby on Rails integrates a lot of things for the developer.

There is ActiveRecord for managing the link between models and the database, migrations for keeping development and live databases in sync, built in testing, the ajax – prototype javascript library is included, and you get a well defined file system structure. While it may not all be packaged together as well, PHP can do all of the above.

Thank you for reading this and I would love to read your comments!

written by Lee

13 Responses to “PHP vs Ruby – Practical Language Differences”

  1. IronRuby Says:

    Hi,
    Really a nice comparison here.
    I would rather suggest/request you to come out with part -2 comparing the PHP5 with IronRuby ( A dot net version for Ruby )
    Since you have already worked with Asp.Net in the past, you can easily compare it. IronRuby is sure to turn out to be the most popular Language that can take many advantages simultaneously…
    (1) Ruby language (2) Dot Net Framework (3) LINQ Advantage (4) Good IDE support (5) Good Document support (6) Ajax Support (7) Great OSS Community ( IronRuby code is OSS ) and of course the Hosting Support with SQL 2005 /Oracle and much more
    Do post your comment here on this blog, once you are ready with a comparison.
    http://ironruby.blogspot.com
    Thanks
    IronRuby

  2. Sarfaraz Says:

    Hi, Well I have been developing with PHP 4 Mysql for last 5 years and have always found PHP evolving drastically over this period of time. With PHP 5 and OOPs PHP has become powerfull and my mindset for developing PHP application more strong until I was told about Rails by one of my friends and I starting exploring. I found it real fast in development and I rewrote a CMS in Rails which i wrote in PHP which is handling majority of my sites in 2 flat weeks which took me about 45 days in PHP. I loved the overall structure of OOPs in Rails but when i wanted it to deploy on my web server I found that it was too tedious and not worth taking the risk of doing R&D in production environment. I have been following codeigniter for sometime now and started working on it and found it equally easy as Rails with my favorite PHP in picture. I have rewrote the CMS using Codeigniter and it is doing wonders. My over site has seen more 30% performance boost which is cool. I am waiting for PHP 6 and codeigniter support for it. I m sure it would be another revolution in web industry.
    By the way this article is good. Really loved reading it. Would love to hear from the author directly.
    Sarfaraz Momin. Lead Web Developer. Acenetaxis Infosystems. Mumbai. India.

  3. pcdinh Says:

    I dont think CodeIgniter is first-class PHP framework these days. Zend Framework, SolarPHP, CakePHP, Symfony or Akelos is much more better in term of code quality and architecture.
    IronRuby sucks. It is a crappy product from Microsoft world. Who care a Windows only product. It is an open source project without community.
    Ruby on Rails is a good web framework. It brings productivity as same as Zend Framework, CakePHP or SolarPHP. But it is much slower, less scalable and less flexible.
    Although Ruby on Rails is not impressive as top-notch PHP frameworks but Ruby is a great language. I love it more than Python and Perl. What Ruby needs to do right now is its compiler’s execution speed.
    PHP has namespaces

  4. Matthew Says:

    You’ll find that that link about namespaces in PHP is actually in relation to the yet un-released version of PHP 6 (release = stable release). (Which, mind you, cannot come fast enough).

  5. John Joyce Says:

    Hosting Rails is not expensive. You can host it at Dream Host!! or any other shared host that provides Ruby/Rails and shell access with fcgi. Rails and Ruby are currently slower than PHP in many situations. No doubt about that. But far easier to learn, use, and maintain. VPS hosting is appropriate for Python based frameworks as well as Rails, and for anything big and serious, it is not expensive, it is the correct way to scale up for higher traffic sites. From there you scale up to dedicated hosting. Beyond that, you can look forward to the soon to come Ruby 1.9 or 2.0 (whatever it will be when it is released) as being much faster, as well as Rails 2.0 (probably dependent on the next Ruby) There is also JRuby, a Java based implementation of Ruby that is making huge advancements at an incredible pace, and will soon preclude the need to know Java even!

  6. Nate Klaiber Says:

    @pcdinh Please site specific examples that Rails is ‘much slower, less scalable and less flexible.’ This kind of FUD gets spread around all of the time, with no facts to back anything up. You can’t point to a specific deployment environment, because it could be different from one setup to another. Having worked with both Rails and PHP, I know that each has their bottlenecks with poor programming, but that lies with the programmer – not the language or framework.
    Also, Ruby on Rails is not as impressive as top-notch PHP frameworks? Please explain to me why the top notch PHP frameworks all came out AFTER RoR, and they all attempt to imitate the RoR functionality? How then is Rails not as impressive? Im not bashing. I used CakePHP at a previous place of employment and absolutely loved it. If I had to do other PHP jobs I would use it, hands down. They have great documentation and a good core team. BUT – they still play catch up, or have to make convoluted workarounds, to achieve what Rails does out of the box. This has more to do with Ruby being a true OO language, versus PHP’s tacked on OO. Again, this just seems like more FUD without any details – could you provide more?

  7. Bob McCormick Says:

    What I’d REALLY like to see is a comparison with the new Zend Framework and Rails.
    The Zend framework has finally come out of beta and looks very promising to me, though I haven’t had time to play with it much yet.
    I played with Rails quite a bit and loved many of the concepts, but for me the deployment killed the deal. Also, having no possible way to protect source code for commercial apps kinda pushed me back to Zend.
    I’ll be looking hard at Zend Framework for my next project to see if it can cut down on development time as much as the Rails dev time. Deployment is certainly easier – have already confirmed that.
    Any thoughts on comparing these two? Zend’s website has a banner that is stating that over 2 million downloads have transpired, so wondering if this framework is going to be the ‘One’ that can take on the Rails jaugernaut. Will certainly be interesting to see some comparisons as time moves on.

  8. D.h. Says:

    The only PHP framework comparable to Rails in terms of functionality out of the box is Akelos.
    They have directly ported Rails to PHP and it works fantastically.

  9. Lee Says:

    I know that Yahoo! selected Symfony for their Yahoo! Bookmarks application. Does anyone know of any other examples of any PHP frameworks being used in significant, production applications? Of course, there are all the basecamp applications using Ruby on Rails. It would be interesting to see which PHP frameworks people are choosing for their applications. Any thoughts?

  10. logical Says:

    Whenever you see one of these comparisons, efficiency and server load are never tested.
    I have used both ruby and php for years. The opinion of myself and many other professionals is that if you think and breath OOP, then you are going to do far better with PHP. Not to mention the efficiency considerations.
    As for speed of coding, I would challenge those who post “make a blog in 15 minutes using ruby” tutorials. My experience is that my PHP teams have completed entire, production quality projects in consistently fractions of the time as the ruby teams.
    Maybe if you’re making a ‘hello world’ blog, you might get it done a few minutes faster, but if you’re designing a full featured object oriented application, PHP will yield secure, comprehensive, maintainable code with a development time that rivals the toughest competitors.

  11. OHR Says:

    So many development languages now, why a new one come out? I get a ruby project source, but I can not runt it properly… it’s a pain

  12. Mason Says:

    I posted this elsewhere, on a site that commented on your article, but I thought I’d leave it here as well.

    “Nevertheless both languages can do almost the same things. Both languages have try/catch/throw style exception handling. Exceptions are new to PHP5 as PHP4 does not have them. Both languages can be used in an object oriented way.”

    Eww. Ruby is a pure-OO implementation. PHP’s was tacked on at the end. The result? Nasty hierarchy polymorphism and introspection. Actually, nasty introspection in general. That’s the reason you can’t do ActiveRecord in PHP the way you can in Ruby.

    If you instantiate B, a child of A, and ask A what kind of object it is (through some method in A), it will say A in PHP, and B in Ruby. The correct answer should be B.
    “Both languages have additional functionality that can be added through libraries.”
    Ruby also supports Mixins, which is why Rails has all those pretty ‘acts as’ decorators. Acts as List. Acts as Authenticated. These little bits are the parts that make Rails a joy to work in. Free functionality across objects without cluttering your code.

    “I have not yet run into a time when I was working with one language and hit a road block where the language I was using was not capable of expressing the functionality I needed. Sometimes things are easier in one language versus the other but both PHP and Ruby have been able to “do” the same things.”

    The joy in programming in Ruby is that you can express more with less code, and in a clearer fashion. Yes, PHP can do:

    for($i = 0; $i
    but Ruby can do:
    3.times { |i| puts i }

    or

    3.times do |i| puts i end

    I think that’s pretty cool.

    “As the owner of a web development company many of our smaller clients do not have the budget for their own VPS account and even if they did, we don’t have the staff to manage a large number of VPS accounts or dedicated servers.”

    Linode VPS starting at $19/mo. Spend a little more and throw multiple hosts on there.
    “For large projects, it may be worth the trouble, but for small to medium sized projects, PHP is much easier to deploy, less expensive to host, and the language is capable of taking on everything those types of sites require.”

    PHP is easier to throw together… but there’s an awesome feeling in properly deploying a Rails app using a Capistrano setup. Not only do you have versioned code, because you’re using Subversion, but you also have versioned releases, with the ability to roll back at any time. Need to add a machine? Throw it in your deploy.rb file and redeploy.
    “For our projects, development time with PHP is not noticeably longer than with Ruby on Rails. Ruby on Rails integrates a lot of things for the developer.”

    Unless his projects are all “hello world”, I find this hard to believe. Once you have even a little fluency in Rails, your dev time will drop. This past weekend was the Rails Rumble, where 150 teams developed 150 full applications. While some of them are a bit lame… it’s amazing to see what people could throw together in 48 hours using Rails. Try doing that with PHP or a PHP framework, and I’d be surprised if you could hit half the high points they did.

    “There is ActiveRecord for managing the link between models and the database, migrations for keeping development and live databases in sync, built in testing, the ajax – prototype javascript library is included, and you get a well defined file system structure. While it may not all be packaged together as well, PHP can do all of the above.”

    This paragraph is what I hated most. He goes on listing all the positives on Rails, and how well it executes on these points, and then goes on to say, “While it may not be packaged together as well…”—that, my friend, is the REASON Rails took off. Rails is a collection of Gems… ActiveRecord, ActionPack, ActionView, etc, but it’s put together in a such a way that it totally enables the developer to do marvelous things in little time.

    I don’t get it.

  13. funkengrooven Says:

    Mason I am not sure what you mean by:
    If you instantiate B, a child of A, and ask A what kind of object it is (through some method in A), it will say A in PHP, and B in Ruby. The correct answer should be B.

    < ?
    class a { function x() { echo “
    b is an instance of : ” . get_class($this); } }
    class b extends a {
    }
    $b = new b(); echo “
    b is an instance of : ” . get_class($b); $b->x();
    ?>

    yeilds

    b is an instance of : b b is an instance of : b
    As I would expect.

Leave a Reply