Federico Cargnelutti

Simple is better than complex. Complex is better than complicated. | @fedecarg

Archive for August 2008

Customize the Symfony Web Debug Toolbar

leave a comment »

Fabien Potencier wrote:

The Symfony Web debug toolbar is one of the developer best friend. It is always conveniently accessible in the browser when using the development environment. It gives you everything you need to know about the current page and ease the debugging of your applications. Until now, the information in this toolbar was hardcoded. But as of Symfony 1.2, the Web debug toolbar is entirely configurable. The new toolbar is composed of panels. Each panel is composed of a title and an optional panel content, and the panel is represented by a PHP object.

sfWebDebugPanelAssets class

class sfWebDebugPanelAssets extends sfWebDebugPanel
{
  public function getTitle()
  {
    return 'assets';
  }

  public function getPanelTitle()
  {
    return 'Stylesheet and JavaScript files from sfWebResponse';
  }

  public function getPanelContent()
  {
    return null;
  }
}

frontendConfiguration class

class frontendConfiguration extends sfApplicationConfiguration
{
  public function configure()
  {
    $this->dispatcher->connect('debug.web.load_panels', array($this, 'configureWebDebugToolbar'));
  }

  public function configureWebDebugToolbar(sfEvent $event)
  {
    $webDebugToolbar = $event->getSubject();
    $assetsPanel = new sfWebDebugPanelAssets($webDebugToolbar);
    $webDebugToolbar->setPanel('assets', $assetsPanel);
  }
}

Links

Written by Federico

August 28, 2008 at 3:18 pm

Posted in Frameworks, PHP, Programming

Kenneth Downs: Why I do not use ORM

with 4 comments

A thorough knowledge of database behaviour tends to lead a person away from ORM. First off, the two basic premises of ORM are factually incorrect: One, that there is some native incompatibility between databases and code, and two, that all the world must be handled in objects. These two misconceptions themselves might be excusable if they turned out to be harmless, but they are far from harmless. They promote a wilful ignorance of actual wise database use, and in so doing are bound to generate methods that are inefficient at best and horrible at worst.

Kenneth Downs: Why I do not use ORM

Written by Federico

August 25, 2008 at 1:24 pm

Identifying Senior Software Engineers

leave a comment »

For HR and legal purposes, most development companies classify Software Engineers into ranks from 1 to 4 (or 5). The higher the rank, the higher the responsibilities, expectations, independence and pay grade. To cut it as an interviewer and manager, you’ll need to classify people accurately with a minimum amount of direct personal exposure: a non-ideal but practical requirement of most hiring processes.

So, how do you objectively identify senior engineering qualities? Preston Lee focuses on several key factors always present in quality engineers, independant of language and platform.

Identifying Senior Software Engineers: Six Critical Differences

Written by Federico

August 25, 2008 at 1:06 pm

6 Different Ways to Testing a Web Service

leave a comment »

This tutorial by Charitha Kankanamge takes you through different approaches to testing Web services.

There are multiple approaches to invoking Web services, regardless of the platform or technology used to built such services. If a service consumer has access to the contract (WSDL) file of a given Web service, then, that particular service can be invoked via either a tool or a client application, whichever is the preferred option. This tutorial focuses on six different approaches to testing and invoking Web services.

6 Different Ways to Testing a Web Service

Written by Federico

August 25, 2008 at 1:00 pm

Posted in Tools, Web Services

Propel 1.3 uses PDO instead of Creole

with 3 comments

In a move to increase performance and take advantage and support new PHP features, Propel 1.3 uses the native PDO database abstraction layer. This change has a number of implications, particularly for those who are executing SQL directly. PDO’s API is loosely similar to Creole’s, so this change shouldn’t require any major re-architecture.

New Features

The new features in Propel 1.3 that will affect upgrading are:

  • New PHP minimum requirements
  • Use of PDO instead of Creole
  • New DSN format for build and runtime properties
  • New transaction API
  • Some method signature changes
  • mysqli adapter is obsolete & has been removed
  • New SPL autoload integration
  • Some API changes for extending classes.

Symfony 1.2

Propel 1.3 will be the default version of Propel bundled with Symfony 1.2. If you can’t switch to Propel 1.3 for whatever reason, you will still be able to use Propel 1.2 by installing the sfPropelPlugin.

DbFinder plugin

The DbFinderPlugin is a symfony plugin that provides an easy API for finding Model objects, whether the underlying ORM is Propel or Doctrine. The idea behind this plugin is to write queries to retrieve model objects through an ORM, but fast. Inspired by Doctrine, Rails has_finder plugin and SQLAlchemy, DbFinder can be seen as “jQuery for symfony’s model layer”. It also aims at putting the things in the right order, meaning that writing a find() query will feel natural for those familiar with SQL.

Related article: The ORM isn’t important anymore

Written by Federico

August 23, 2008 at 10:47 pm

Posted in Databases, Frameworks, PHP

Refactoring the Front Controller of the Zend Framework

with 8 comments

One of the most fundamental decision in object design is deciding where to put responsibilities. No one, and I mean no one, gets it right the first time. That’s why refactoring is so important. As Kent Beck puts it, refactoring is the process of taking a system and adding to its value, not by changing its behaviour but by giving it more of these qualities that enable us to continue developing at speed.

Extract Class Refactoring

You’ve probably heard that a class should handle a few clear responsibilities. In practice, classes grow. You add some operations here, a bit of data there. You add a responsibility to a class feeling that it’s not worth a separate class, but as that responsibility grows and breeds, the class becomes too complicated. Extract Class is a common technique for moving features between objects.

Extract Class:

You have one class doing work that should be done by two.

Zend Framework

Zend Framework organizes code in a project structure and puts the project files into different directory structures:

  1. MVC directory structure
  2. Modular directory structure

The framework allows users to choose between one or the other. My goal is to move this responsibility away from the Zend_Controller_Front class. To do this I need to use the Extract Class to alter the internal structure of the class without changing its external behaviour. This refactoring will reduce the complexity of the Front Controller and increase its flexibility. Also, it will allow users to define custom directory names and paths.

First, I need to identify the methods I want to extract from the Zend_Controller_Front class:

addControllerDirectory()
setControllerDirectory()
getControllerDirectory()
removeControllerDirectory()
addModuleDirectory()
setModuleControllerDirectoryName()
getModuleControllerDirectoryName()

Then, I need to create a set of classes to express the split-off responsibilities:

Zend_Controller_Directory_Abstract
Zend_Controller_Directory_Exception
Zend_Controller_Directory_Application
Zend_Controller_Directory_Module

And finally, I need to use Move Field and Move Method to move fields and methods over from Zend_Controller_Front to the new classes.

abstract class Zend_Controller_Directory_Abstract
{
    public function setControllerDirectoryName()
    public function getControllerDirectoryName()
    public function setControllerDirectory()
    public function getControllerDirectory()
    public function addControllerDirectory()
    public function removeControllerDirectory()
}

class Zend_Controller_Directory_Application
  extends Zend_Controller_Directory_Abstract
{
    public function addApplicationDirectory()
    public function setApplicationDirectory()
    public function getApplicationDirectory()
}

class Zend_Controller_Directory_Module
  extends Zend_Controller_Directory_Abstract
{
    public function addModuleDirectory()
    public function setModuleDirectory()
    public function getModuleDirectory()
}

All I need to do now is add a setter and getter method to the Zend_Controller_Front class and inject the object. For the sake of this example, I’ll assume that I can add additional methods to the Zend_Controller_Front class.

class Zend_Controller_Front
{
    public function setDirectory(Zend_Controller_Directory_Abstract $directory)
    {
        $dirs = $directory->getControllerDirectory();
        foreach ($dirs as $module => $dir) {
          $this->getDispatcher()->addControllerDirectory($dir, $module);
        }
        $this->_directory = $directory;
    }

    public function getDirectory()
    {
        return $this->_directory;
    }
}

Before:

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->addControllerDirectory('../application');
$frontController->setModuleControllerDirectoryName('controllers');

After:

$directory = new Zend_Controller_Directory_Application();
$directory->setControllerDirectoryName('controllers');
$directory->addApplicationDirectory('../application');

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setDirectory($directory);

That’s it. I’ve demonstrated how to refactor the Front Controller of the Zend Framework using a refactoring known as “Extract Class”. Martin Fowler discusses this technique in “Refactoring: Improving the Design of Existing Code“.

Links

Written by Federico

August 20, 2008 at 3:10 pm

Working with legacy code

leave a comment »

Most projects carry some amount of legacy code. You can’t work very fast with a legacy code base, but you can speed it up if you establish a strategy to deal with your existing code and mitigate risk as new development goes forward.

What is Legacy Code?

Legacy code is code from the past, maintained because it works. But, for people who deal with it day in and day out “legacy code” is a pandora’s box: sleepless nights and anxious days poring through bad structure, code that works in some incomprehensible way, days adding features with no way of estimating how long it will take. The age of the code has nothing to do with it. People are writing legacy code right now, maybe on your project.

The key to working effectively with legacy code is getting it to a place where it is possible to know that you are making changes one at a time. When you can do that, you can nibble away at uncertainty incrementally.

Legacy Management Strategy

By itself, legacy code doesn’t hurt anything. As long as it works, it only becomes painful when you have to make modifications. Fortunately, the first steps you have to take to work effectively with legacy code also make it easier to clean things up.

  1. Identify change points
  2. Find an inflection point
  3. Cover the inflection point
  4. Break external dependencies
  5. Break internal dependencies
  6. Write tests
  7. Make changes
  8. Refactor the covered code

These steps are explained in more detail in the article Working Effectively With Legacy Code (PDF), written by Michael Feathers.

Written by Federico

August 20, 2008 at 1:45 am

Hackers and Painters

leave a comment »

Here’s an article published by Paul Graham in 2003 that’s worth reading.

“I’ve never liked the term “computer science.” The main reason I don’t like it is that there’s no such thing. Computer science is a grab bag of tenuously related areas thrown together by an accident of history, like Yugoslavia. At one end you have people who are really mathematicians, but call what they’re doing computer science so they can get DARPA grants. In the middle you have people working on something like the natural history of computers– studying the behaviour of algorithms for routing data through networks, for example. And then at the other extreme you have the hackers, who are trying to write interesting software, and for whom computers are just a medium of expression, as concrete is for architects or paint for painters. It’s as if mathematicians, physicists, and architects all had to be in the same department.”

Continue reading: Hackers and Painters

Written by Federico

August 19, 2008 at 12:36 am

Posted in Programming

No need for set/get methods in Python

with 17 comments

Python code doesn’t typically use the get and set methods so common in PHP. Normally, when writing PHP code, you carefully protect your instance variables by making them private, so callers can only interact with them via getter and setter methods. For example:

class Book {
  private $title;

  public function setTitle($title) {
    $this->title = $title;
  }

  public function getTitle() {
    return $this->title;
  }
}

$book = new Book;
$book->title = 'Code Complete';

However, in PHP, the code above returns the following error:

Fatal error: Cannot access private property Book::$title

Python’s solution to this problem is more readable, it has a construct called a “property”. Properties are a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. These are sometimes known as “managed attributes”. Basically, a property is a way to make a function call look like an instance variable reference. For example:

class Book {
  private $title = property(getTitle, setTitle);

  public function setTitle($title) {
    $this->title = $title;
  }

  public function getTitle() {
    return $this->title;
  }
}

$book = new Book;
$book->title = 'Code Complete';

Whenever someone writes $book->title, they’re really calling $book->getTitle(). Although the class has getters and setters, the callers of the class still get to use the original, simpler, easier-to-read syntax for accessing the value.

This way you get the best of both worlds: clean and simple client access to your class, and protection and flexibility within the class.

Examples

Python (run code)

class Book(object):

    def get_title(self):
        return self._title

    def set_title(self, title):
        self._title = title

    title = property(get_title, set_title)

Book.title = 'Code Complete'

PHP (run code)

class Book {
  private $title;

  public function __get($property) {
    $method = 'get' . ucfirst($property);
    if (!method_exists($this, $method)) {
      throw new Exception('No such method: ' . $method);
    }
    return $this->$method();
  }

  public function __set($property, $value) {
    $method = 'set' . ucfirst($property);
    if (!method_exists($this, $method)) {
      throw new Exception('No such method: ' . $method);
    }
    $this->$method($value);
  }

  public function setTitle($title) {
    $this->title = $title;
  }

  public function getTitle() {
    return $this->title;
  }
}

$book = new Book;
$book->title = 'Code Complete';

As you can see in the example above, PHP allows you to do something similar using the __get and __set methods, but can be a bit tricky to get right. Python’s “property” construct lets you do this painlessly.

Written by Federico

August 17, 2008 at 5:12 pm

Posted in PHP, Programming, Python

Microsoft Enviroment video reveals datacenter server numbers

leave a comment »

A recent promotional video produced by Microsoft’s Environmental Sustainability group revealed how many servers Microsoft actually has.

Some quick stats gathered from the video: 15 datacenters hosting 148,357 servers sitting on 17,406 racks consuming 72,500KW of utility power as of the end of January 2008. If you’re a bit of a imperial measurement person, that’s 97,000 horsepower.

Written by Federico

August 16, 2008 at 4:24 pm

Posted in Web

Follow

Get every new post delivered to your Inbox.

Join 1,033 other followers