OOP in PHP

This is a really old entry — I will no longer vouch for its sanity. :)

Ah, you gotta love Object Oriented Programming in PHP. It’s got the modular, extensive way of coding in C++, and the simplicity of PHP. This has become pretty obvious during the work with LANtools version 2. Just look at this code sample from LANtools version 1 (this snippet is from the “show user” page, which is one of the simplest parts of the whole thing):

<h3>Vis bruker</h3>
<?php

$result = mysql_query("SELECT * FROM users".
                      "WHERE id = ".quote($_GET["user"]));
    
if (mysql_num_rows($result) == 0)
{
  echo "<p>\n  Ugyldig bruker.\n</p>\n";
}
else
{
  $row = mysql_fetch_assoc($result);

?>
<table <?=tableStart()?>>
  <tr><td><b>Nick:</b></td>
  <td><?=formatField($row["username"])?></td></tr>
  <tr><td><b>Fullt navn:</b></td>
  <td><?=formatField($row["realname"])?></td></tr>
  <tr><td><b>Bursdag:</b></td>
  <td><?=formatDate($row["birthday"])?>
  (<?=floor((time()-strtotime($row["birthday"]))/
  (60*60*24*365))?> år gammel)
  </td></tr>
</table>

I’d say this is pretty messy and unmanagable. Now take a look at this code, from LANtools version 2:

<?php

$user =& $root->getUser($_GET["user"]);
    
if (!$user) {
  error("INVALID_USER_ID");
  return;
}
    
assign("user", $user);
display();

?>
PHP code (./modules/user/view.php)

{header}Vis bruker{/header}
<table>
  <tr>
    <td><b>Nick:</b></td>
    <td>{$user->username|formatField}</td>
  </tr>
  <tr>
    <td><b>Fullt navn:</b></td>
    <td>{$user->realname|formatField}</td>
  </tr>
  <tr>
    <td><b>Bursdag:</b></td>
    <td>{$user->birthday|formatDate}
    ({$user->getAge()} år gammel)</td>
  </tr>
</table>
Template code (./templates/default/user/view.tpl)

So much cleaner. It’s a real pleasure to work with. :)

Posted in PHP

Comments