Modern Design in PHP

Posted by acts_as_flinn Sun, 19 Aug 2007 04:57:00 GMT

Yesterday I finished my first week at my new job. Going back to the PHP world is somewhat shocking to see a complete lack standardized coding methods. I spent some time this week getting to know the project I’ll be helping out on for the next several weeks. The code originates from an overseas outsourcing company with absolutely no standards or knowledge of design patterns, or concept of writing DRY code.

I find it difficult sometimes to get the concepts I’ve picked up during Ruby development across to PHP programmers. Since most people self-learn PHP there is a tendency to do a lot of brute force coding, copying and pasting and doing stupid stuff like using template languages when there is know need to use a templates. Because they self learn, modern software engineering philosophies and management techniques that are progressing the state of the art are virtually unheard of by many PHP developers. Let’s explore some of the things PHP developers could be doing to make their lives better, save their employers money and maybe get a raise.

Views Instead of Templates

In the PHP world there is this mysterious draw toward templating using engines like Smarty, Flexy (which I have been guilty of), Blitz or any of the other engines available. I think this draw is the experience of the developer wanting to abstract and separate the presentation layer. It’s a natural progression that comes from experience – the kind of experience you get from PHP’s free style – so free that you often see SQL statements, and HTML markup embedded within the same PHP script.

So why use a template engine in the first place? PHP is a template engine. The only valid reason I have ever found is for applications that allow either designers or end users change the front end presentation layer – and even then I’m skeptical what with the whole existence of CSS…but I can understand the level of flexibility templates allow a designer. A good example that I have used is Shopify use of the Liquid Markup Language which was created for Shopify. Anyway, back to the subject.

If there is no reason for a third party designer to change the presentation layer there is almost no need for a template language, but you see templating in PHP frequently used as a way to force code separation.

So PHP coders pay attention… Forget the template engines unless you really need them they only indirectly force you to do code separation, slow down your application, learn a bunch of additional syntax and limit your ability to present what you want to in PHP. Just chose to do code separation from the design phase of your application. Keep the power of PHP available in your presentation layer views and skip learning a pointless template language.

Testing, Testing, 1. 2. 1. 2.

How do we test in PHP? Write a script, hit the browser and look all over the place to see if what you wrote worked). WRONG Well not really – most PHP developers do just that. No automated unit testing or integration testing, and most have never heard of it. I’ll be the first to admit that when I made the leap from PHP to Ruby I had never heard of unit testing and didn’t incorporate testing until after at least a year of Rails development. I’m also the biggest advocate for automated testing.

People often resist writing automated tests because they can be time intensive at the onset of a project. It’s often a matter of “we don’t have enough time or funds to spend writing tests.” The proponents of this argument are usually the ones in favor of brute force eye ball tests. “Let’s make a change and cross our fingers hoping it doesn’t break anything we’ve already eyeballed.”

Well that just doesn’t make any sense! It’s a business decision that budget managers should understand. Why spend more time eyeballing and crossing your fingers when PHP has unit tests, continuous integration tests and a other great methods. Managers should be asking their developers why they aren’t using PHP’s automated testing facilities!

Data Modeling and Class Design

I do my little turn on the cat walk, yeah on the cat walk… Modeling seems to be an esoteric subject for some PHP developers. In a lot of database schemas I repeatedly see weird table layouts, aggregate data storage and lots of abbreviations. In Ruby on Rails the convention is to model tables based on object usage. We use the Active Record design pattern. PHP developers often think ActiveRecord and Active Record are one and the same – they’re not.

Active Record the design pattern is a description for creating classes that relate to a row in a database, provide static finder methods and implement an object that both provides an interface to data and the methods to store, destroy and modify the data. The pattern is impossible to simply implement in PHP. But that doesn’t mean it can’t be used to the fullest of PHP’s ability or that you can’t implement the next best data design pattern.

Why use abbreviations in database tables? Is it really that convenient to abreviate the hell out of every variable or attribute name? One of the best things you get in Rails is string inflection (huh?). That means we can take a string like “phone_number” and call a method like humanize resulting in a human readable field label, “Phone Number” – using this is a no brainer. It also makes it a lot less tempting to use variable names like “phonum”...but that’s really a no brainer too.

What looks better to the human eye? “phonum” or “phone_number” – you can see where this is going… ”$phonum”, ”$cli_phonum”, ”$client_phonum”, ”$client_phone_number”, ”$client->phone_number”. So if you were working in a team what convention works best, esoteric abbreviations or human readble variable names that any programmer can jump into without a secret decoder ring.

If you’ve got a form full of aggregate information keep it separate. This is an easy one – when you’re on the receiving end of a post why reassemble your information?

HTML


<input type="text" name="client_name" id="client_name" value="Joe Smalltime &amp; Son" />
<input type="text" name="client_email" id="client_email" value="" />
<input type="text" name="client_login" id="client_login" value="" />
...

PHP


$client = array();
$client['name'] = $_POST['client_name'];
$client['email'] = $_POST['client_email'];
$client['login'] = $_POST['client_login'];
...

Or do nothing..

HTML


<input type="text" name="client[name]" id="client_name" value="Fortune 500 Corp." />
<input type="text" name="client[email]" id="client_email" value="" />
<input type="text" name="client[login]" id="client_login" value="" />
...

PHP


$client = $_POST['client'];

Do what you mean, and only that.

Why make things more complex than they need to be? If you mean to take information from the web and save it, do just that. Where should we validate information, every script that needs to accept and save information or in the one place it actually matters? Why validate manually in every script when we can set our validation conditions at the class level then do what we mean? What am I talking about?


if (valid_client_info($_POST['client_info']) {
  save_client_info($_POST['client_info']);
} else {
  throw new Exception("Your client info sucks");
}

Or we could do this…


  $client = new Client($_POST['client']);
  if ($client->save()) {
    $this->render_string("Hazaa!");
  } else {
    throw new Exception("argh!");
  }

Conclusion

PHP developers can learn a lot from Ruby on Rails. You really don’t have to use Ruby to take advantage of modern design techniques but what a lot of people fail to realize about Rails is the fact that most of the conventions weren’t designed just for ruby – Rails is a laundry list of best practices for web development. Some of the best developers in the world are using Rails because of it’s best practices that enable rapid development and get you focused on the business logic not the repetative tasks you face every project.

Quercus: PHP's jRuby

Posted by acts_as_flinn Sat, 11 Aug 2007 03:08:00 GMT

Again I’m investigating interesting things for the new job I start next week. I just came across Quercus which appears to be a complete implementation of PHP5 in Java. It even includes the ability to import Java classes into PHP. It also provides bytecode caching ala APC for a nice 3-5x speed improvement over plain old mod_php. This is akin to Ruby’s jRuby which provides just about the same feature set. The code looks like it already offers good compatibility but needs more attention…any Sun executives reading? ;-)

PHP and ActiveRecord (continued)

Posted by acts_as_flinn Fri, 10 Aug 2007 19:55:00 GMT

Today I saw a big traffic increase from my PHP and ActiveRecord post. It looks like PHPDeveloper posted a link to the article and response, so I’ve written a response to the Arnold’s wor(l)ds response post. Arnold’s post is insightful, references runkit and has a good implementation of a Sortable tasklist example in PHP.

In Ruby everything is an object. A Ruby object that is.

When I was working on Biscuit I longed for a working implementation of runkit. I experimented with it and it did offer exactly what I wanted but it lacked widespread deployment because of and stability. After two years I don’t think much progress has been made (not to take anything away from the author). I think runkit is a hack, a dangerous one too. Here is another example of why Ruby is better.

In PHP if you want the features runkit offers (add super globals, modify class methods at runtime, etc.) you have to hack the engine at the internal C/C++ level, meaning you have to completely control the development, testing and production environments, track source changes, hope nothing breaks… You might as well be forking at that point.

If you want to hack something in the Ruby kernel methods, you just monkey patch – equally dangerous on kernel methods BUT limited in scope…in Ruby you’re not destroying Ruby with monkey patches. You might kill your own application but other applications that don’t share the same instance are not effected.

Lineage

PHP and Ruby have a lot in common, they both derive a certain expressiveness found in Perl, and they are scripting languages with low overhead and a quick learning curve. They’re also different in a number of ways, and I think that can be chalked up to lineage. One could argue that PHP’s design is derived from C++ and Perl and maybe even Java lately.

One would also be able to argue that Ruby derives its design from Smalltalk/Strongtalk and Perl. So the reason a lot of PHP users probably like Ruby is it’s light weight scriptyness and Perlish feel (I know I’ll take crap from Perl, PHP and Ruby developers for that one). But because of the lineage we see straight line inheritance and interfaces in PHP and in Ruby we see mix-ins. Back to Arnold’s article.

How to not write a shitload of code using Ruby Mix-Ins

Arnold next addresses the issue with mix-ins showing his implementation of a sortable class in PHP. His implementation is good but it’s a lot of work compared to just expressing acts_as_list in Ruby. Most people might see this as splitting hairs but it’s not for anyone actually wondering. In Ruby you need exactly 1 (user) class to handle this sort of functionality – the difference being that the Class is the list in Ruby.

In the PHP example you need a TaskList and a Task and since Sortable is only an interface you’ve actually got to write the methods to implement them in your own (user) class. Again, you’re saying “big woop”...well the woop is the fact that you can’t do mix-in style inheritance like this because your class needs to inherit the methods to make them work anything like acts_as_list, ie. by not writing a shitload of code for every sortable class.

The second example demos a sortable runkit implementation. This is really similar to saying PHP6 will have the keyword static to solve the issue with static property inheritance.

The problem with static inheritance in PHP

I’ve seen people describe static property inheritance as a problem, and I’ve probably been guilty of it myself. Well it’s not really a problem. Static properties shouldn’t inherit. The PHP developers have said time and time again they are not changing this, it works how it is supposed to work.

As far as runkit goes, It seems pretty crazy to have an engine level hack + runtime interferance with a class to overcome this issue.

Over and over again when I see this coming up as an “issue with PHP” I remember grappling with it with Biscuit. The theme that I keep seeing when people try to describe this problem has to do either with identifying the calling class using an inherited static method. In other words, people are usually trying to do this:


Class Base {
  static public name() {
    return get_class(self);
  }
}

Class My Extends Base { }

echo My::name(); #=> Base but everyone wants My

They’re usually trying to implement some form of ActiveRecord a factory method or something similar. From what I’ve seen on how PHP6 will be re-using the static keyword and implementing namespaces this problem won’t be fixed like I had hoped.

What PHP6 Actually Needs

There’s an article entitled What PHP6 Actually Needs and you could almost retitle the article Things Ruby has and PHP doesn’t. So if some many good programmers are asking for these features why aren’t they getting them from Zend and PHP6?

A question that Ruby enthusiasts might ask is why are so many PHP developers asking for these features and still not using Ruby??? I think for Ruby it has a lot to do with deployment issues – fast_cgi sucks, ligthttpd you have to jigger with, mongrel and just about every other deployment solution is akin to setting up an application server. For smaller apps that a lot of PHP developers work on having to go through this crap just for a small program is prohibitive.

So I guess this continuation of the original article seems like an attack on PHP. It’s not…it is a continuation about why ActiveRecord works really well in Ruby and not so good in PHP. But there is hope. After looking at the Row Data Gateway pattern I’m thinking a really good implementation can be done in PHP that would give similar flexible muscles for PHP database driven development.

Older posts: 1 2