Why are they still writing crappy code?

At work, I'm currently working with Wordpress and I was amazed at how most plugins are really bad written! PHP developers should really start to make an effort about that and this is even more true for popular projects like Wordpress. At least, the core or the Akismet plugin, which comes already installed, should give an example. But no! Have you ever had a look at this plugin source code? I nearly puked! Come on guys, not even comments ? Don't be surprised why enterprise are a bit reluctant to use PHP.

Most plugins don't use classes, don't comment their code, HTML is in the middle of PHP code...all anti pattern or bad practices can be found in these. While Wordpress does not force you and does not provide means to facilitate clean programming, it is still not a reason to not use it. It is fairly simple to separate HTML from php files and use a class for the plugin. Here how I did it (and I'm sure there's even a better way but at least this one is cleaner than most plugin).

In your plugin file, starts by creating a class. I use a start() method which will register all hooks and one method for each of them.

 1 /**
 2  * explain what my plugin does
 3  */
 4 class MyWordpressPlugin
 5 {
 6     /**
 7      * Initialize the plugin and register hooks
 8      */
 9     public static function start()
10     {
11         add_action('hook', 'MyWordpressPlugin::onHook');
12     }
13 
14     /**
15      * Callback for the action "hook"
16      */
17     public static function onHook()
18     {
19         // do stuff
20     }
21 }
22 
23 // starts the plugin
24 MyWordpressPlugin::start();

That's it! Far more cleaner than putting everything in the global scope.

All my HTML content is saved as php files with the phtml extension in an html subfolder. Then for each of them, I create a renderSomething() method which simply includes the phtml file.This method can, before the include, do some logic, like retreiving some data. There should be only presentation logic inside the phtml file.

I also create a separate file with a new class when it comes to create some administration pages. My plugin needed an option page so I create a class called MyWordpressPluginAdmin which registers hooks and do all the suff associated with displaying my option page. Then I include this file in the plugin file and call MyWordpressPluginAdmin::start() from the MyWordpressPlugin::start() method. Here is how it looks like:

 1 /**
 2  * Register the option page
 3  */
 4 class MyWordpressPluginAdmin
 5 {
 6     /**
 7      * Register hooks
 8      */
 9     public static function start()
10     {
11         add_action('admin_menu', 'MyWordpressPluginAdmin::onAdminMenu');
12     }
13 
14     /**
15      * Register the option page
16      */
17     public static function onAdminMenu()
18     {
19         add_options_page('My plugin', 'My plugin', 8, __FILE__, 'MyWordpressPluginAdmin::renderOptionPage');
20     }
21 
22     /**
23      * Render the option page
24      */
25     public static function renderOptionPage()
26     {
27         include dirname(__FILE__) . '/html/option_page.phtml';
28     }
29 }

I think, and correct me if I'm wrong, that this way of doing things is better. The code is commented, easily maintenable, designer could work on their own files... Do you think this is a good solution? the comments are yours!

PS: sorry for the harsh beginning but I was quite angry and disappointed when I saw all that.

Namespace.js

Following my previous article on object oriented programming in Javascript, I released yesterday a small script which allows you to manage namespaces. I know that solutions already exist. Not considering the one from libraries (I wanted a library independent script), I was not satisfied by any of them.

Namespace.js is very simple to use. It contains all common actions encountered when dealing with namespaces. It can import objects in the global scope or include remote scripts based on their namespace. It is very small (5.4 Kb minified), open source and of course library independent.

I published the project on google code at http://code.google.com/p/namespacedotjs

Here are some examples:

 1 Namespace('foo.bar');
 2 foo.bar.myFunction = function() {};
 3 
 4 Namespace('com.example', {
 5    MyClass: function() { return {}; }
 6 });
 7 var obj = new com.example.MyClass();
 8 
 9 Namespace.use('com.example.MyClass');
10 var obj2 = new MyClass();
11 
12 // include com/example/RemoteClass.js
13 Namespace.include('com.example.RemoteClass');
14 var obj3 = new com.example.RemoteClass();
15 
16 Namespace.registerNativeExtensions();
17 'com.foo.bar'.namespace();

Object oriented javascript with Mootools

We've seen a lot of talk lately about OO javascript. I won't come back on that as there's many tutorial and blog posts about it. However, I rarely seen articles about the OO capabilities of Mootools. While every Mootools users are probably aware about it ,Mootools is not the most used framework, and not all javascript developers may now its great features in that field.

Mootools introduces the Class object which allows you to, obviously, create classes. To create a class, you need to create a new instance of this object. Beware that we define the class here, even if we're using the new keyword. The Class's constructor takes as argument an object defining methods and properties.

1 var MyFirstClass = new Class({
2     message: "hello world",
3     sayHello: function() {
4         alert(this.message);
5     }
6 });

As you can see, we can use the this keyword to reference the instance. Creating an instance of the class is straightforward:

1 var obj = new MyFirstClass();
2 obj.sayHello();

While this should seems pretty "standard" for any OO developer, it is not for javascript. The protoype (not the framework) way of doing things, while powerful, is quite awkward! And as we're going to see, Mootools offers much more regarding OO features.

If you're class needs a constructor, you can define a method named initialize

.

1 var HelloWord = new Class({
2     initialize: function(name) {
3         alert('hello ' + name);
4     }
5 });
6 
7 new HelloWorld('peter');

Classes can of course extend each other. Mootools supports only one parent class. It can be defined by adding a property named Extends to your class definition. The property's value must be an object.

 1 var Animal = new Class({
 2     initialize: function(name) {
 3         this.name = name;
 4     },
 5     eat: function() {
 6         alert('yummie');
 7     }
 8 });
 9 
10 var Human = new Class({
11     Extends: Animal,
12     speak: function() {
13         alert(this.name + 'said bla bla bla');
14     }
15 });
16 
17 var peter = new Human('peter');
18 peter.eat();
19 peter.speak();

When subclassing, a method (not only the constructor) can call the same method from its parent class using the this.parent() function.

1 var Peter = new Class({
2     Extends: Human,
3     initialize: function() {
4         this.parent('peter');
5     }
6 });

Class can also use the special Implements property. Do not confuse this with the java or php implements keyword as it does not have the same behavior. In Mootools classes, Implements will merge properties from one or many objects into your class, overriding any method with the same name. It is useful to implement extra class features.

Indeed, Mootools comes with three extra class features: Chain, Events and Options. They can be added to your class using the Implements properties.

1 var MyClass = new Class({ Implements: [Chain, Events] });

Events adds events support with common methods like addEvent(), removeEvent() ... It also adds the fireEvent() method which, as its name implies, fires an event.

 1 var Paul = new Class({
 2     Extends: Human
 3     Implements: Events,
 4     initialize: function() {
 5         this.parent('paul');
 6     },
 7     speak: function() {
 8         this.parent();
 9         this.fireEvent('speaking');
10     }
11 });
12 
13 var paul = new Paul();
14 paul.addEvent('speaking', function() { /* ... */ });

The Chain and Options feature are also pretty neat but I let you check the Mootools documentation on these one.

I've gone through the documented features and we'll now see some less known ones. For example, adding static properties (even if it seems pretty obvious).

1 var MyClass = new Class({ /* ... */ });
2 MyClass.staticProperty = '';
3 MyClass.staticMethod = function() {};

Don't forget to use the class name when calling them (you can't use the this keyword). A common design pattern in OO is Singleton. This can easily be implemented using a closure.

 1 var MyClass = (function() {
 2     var MyClassSingleton = new Class({ /* ... */ });
 3     var instance;
 4     return function() {
 5         return instance ? instance : instance = new MyClassSingleton();
 6     }
 7 })();
 8 
 9 var obj1 = new MyClass();
10 var obj2 = new MyClass(); // same instance, obj1 == obj2

The Extends and Implements properties are called mutators and you can define you're own ones. This can be done by adding a property to the Class.Mutators object named after your special property. This property should be a function with two parameters: the first one will be an object with the class properties and the second one the value of the mutator property. The function must return an object with the class properties.

1 Class.Mutators.MyMutator = function(properties, mutatorValue) { /* ... */ };
2 var MyClass = new Class({ MyMutator: "mutator value" });

I hope I covered most of what is to know about Mootools and classes. I'll soon, probably tomorrow, write an article about javascript and namespaces using a custom library I made.

Updates

I've been pretty busy these days working on Atomik 2.1. I released a second beta yesterday and it's shaping up very well. The final release should be out very soon. Today, I updated my CV and it is now available in English. You can download it on the Resume page.

Atomik 2.1 beta and a revamped website

Finally, Atomik Framework 2.1 beta is out! The changelog is pretty big (for a tiny framework). Here are the main changes:
  • Templates are renamed views
  • Native layout support
  • Native support for the session and flash messages
  • Improved plugin system
  • New utility methods
Also comes with this release an updated documentation and a manual for plugins! But the great thing is the completely revamped website! Much much prettier! There's now a plugins repository where everyone can share their creations. There's also a great distribution builder where you can choose which plugins to include (from the repository), configure the framework and even add a javascript framework! Try it out! http://www.atomikframework.com The final release should come very shortly as this one is already stable.

Blog renaming

As you can see I just renamed the blog name to the bare minimum. I also added a new Projects page where I list all my projects. I will soon update my resume as I'm going to start searching for a summer job some time soon. In the near future I'm also going to diversify articles posted here. Most of them are about PHP. I love PHP and it's my main language. However I also develop in many more and thus, I'll try to also publish articles about these. The blog is now also available from two other domains: http://www.maximebf.com and http://maxime.bouroumeau-fuseau.fr

Dependency injection using Klass

It's been a while since I wanted to create a dependency injection mechanism using PHP but nerver took the time. I wanted it as simple as possible. This morning I woke up and decided it was time! So here is Klass. Only one class which other classes can extend to get their properties injected or it can be use independently. It also provides automatic getters and setters when sublclassed.

Dependency Injection (DI) is described on Wikipedia as:

Dependency Injection (DI) in computer programming refers to the process of supplying an external dependency to a software component.

Klass uses annotations for a smoother coding style. No lines of declarations needed. Just use the @Inject tag on properties where their value should be injected. Use the @Dependency tag on classes that should be injected into properties.
When using the @Inject tag, you must specify the type of the value to be injected. It can be done between parentheses after the tag or using the @var tag (see php documentor). It is also possible to change the type under which a class registers itself as a dependency. It is done the same way as with @Inject.
When the property where @Inject is used is not public, Klass will try to use a setter method.

Dependency injection can also be used on class not subclassing Klass. Using the Klass::create() method, you can create instances of any class that will profit of the injection mechanism. It is also possible to inject objects using Klass::inject(). To register an object as a dependency, use Klass::registerDependency().

 1 class Employee extends Klass
 2 {
 3     /**
 4      * @Inject
 5      * @var Boss
 6      */
 7     public $boss;
 8 }
 9 /** @Dependency */
10 class Boss extends Employee
11 {
12 }
13 class Freelance
14 {
15     /** @Inject(Boss) */
16     public $boss;
17 }
18 
19 $boss = new Boss();
20 $employee = new Employee();
21 $freelance = Klass::create('Freelance');
22 assert($employee->boss === $boss); // true
23 assert($freelance->boss === $boss); // true

Klass also provides automatic generation of accessors (getters, setters, ...) for properties. This can be only done on classes subclassing Klass. Properties that should have accessors must have the @Accessors tag in their doc comment. There is three type of accessors supported: get, set and is. By default, all properties with the tag will have the get and set accessors. is is available with boolean values. It is however possible to enable only specific accessors. Specify them between parentheses and sperated by comasafter the @Accessors tag. If the property name begins with an underscore, it will be removed.

 1 class Employee extends Klass
 2 {
 3     /** @Accessors */
 4     protected $_name;
 5 }
 6 
 7 $employee = new Employee();
 8 $employee->setName('Peter');
 9 assert($employee->getName() == 'Peter'); // true

The @Accessors and @Inject tags can be used at the same time.

I hope this little class will help some of you. This kind of mechanism is very well suited for architecture with many components interacting between each other. I tried to comment the code as much as possible so it can be understand by anyone.

Download klass.zip (with an example) (only 4Kb)

PS: From now on, I will try (and I said try!) to post more articles. If you would like to see articles about a specific subject, don't hesitate to send an email (see the resume section).

Harmony and FireUnit

I don't know if you've seen the news, but yesterday John Resig released FireUnit, a unit testing utility for javascript integrated to Firebug.It seems a great piece of software and it immediately got me thinking about integrating it to Harmony! Some times ago I read a comment about Harmony on onGWT about the fact that frameworks mimicking GWT for other languages were going to harm GWT because they're of lesser quality. It is clear that Harmony is a microbe compare to GWT (and I'm not talking about quality - I think Harmony is "pretty good" when following PHP standards) but I want it to grow! Adding unit testing would be a great step forward! So when I saw the news of FireUnit, it strikes me: it must be integrated into Harmony. Thus, I'm going to start a new package named Harmony_Test which will provide unit testing in php as well as in javascript. You will be able to test your classes in both language so you're sure the translation process has gone well. I hope this new package will show my determination to build an enterprise class framework. I also started a new package yesterday called Harmony_Zend which will facilitate integration between Harmony and the Zend Framework. For the moment, I'm mostly in a refactoring process. I hope to release the first beta before the end of the year...

Enhance CSS with Harmony_Style

As Harmony Framework is greatly shaping up (I'm near beta 1), I would like to present you one of its latest component: Harmony_Style. I developed this component a while ago but never published it. Harmony_Parser originally comes from this package. I decided to integrate it into the framework because I think it's a great fit. But what is Harmony_Style ? In few words, it's an enhance version of CSS. It provides new features over traditional stylesheets. The great thing about it, it's that the syntax does not change so it's easy to learn and compatible will all existing stylesheets.

Nested rules

This is probably one of the most annoying missing feature! You often have to write long selectors where it would be so natural to use nested rules. Using Harmony_Style, simply create rules in other rule definition. The parent selector will be prepended to child rules.

ul.my-list {
    list-style-type: none;
    li {
        margin: 20px;
    }
}

Will output:

ul.my-list {
    list-style-type: none;
}
ul.my-list li {
    margin: 20px;
}

Inheritance

When mutliple rules share the same properties, classes can be used. However in some situations, the targeted element does not have the needed class. Inheritance allows you to add all properties of an existing rule to another one. It's done using the < character, followed by a selector pointing to the rule to copy. Multiple selectors can be used by separating them using comas.

.my-class {
    color: red;
}
#my-element-without-my-class < .my-class {
    margin: 20px;
}

Will output:

.my-class {
    color: red;
}
#my-element-without-my-class {
    color: red;
    margin: 20px;
}

You can of course override any properties.

Constants

Constants allow you to store values that you can reuse in your stylesheets. For example, it can be a list of colors, sizes, fonts... Constants won't appear on the final stylesheet. They start using the dollar sign. There are two types of constants: single value and standard rules. The first one stores only one scalar value. It is defined as follow:

$my-font = arial;
$my-color = #FF0000;

The second type behaves the same way as normal rules:

$sizes {
    small: 10px;
    normal: 12px;
    big: 16px;
}

Rule-like constants can also contain nested rules:

$conf {
    sizes {
        small: 10px;
        /* ... */
    }
    colors {
        red: #FF0000;
        /* ... */
    }
}

You can use constants for inheritance and constants can inherit of any other rules. Now the big question is WTF if I can't use these constants in property values? Here comes embedded queries.

Embedded queries

Embedded queries allow you to fetch any value from any rules. It's normal selectors place between square brackets. It can be used in property and at-rules values.

#my-div {
    color: [$conf colors red];
}
#my-2nd-div {
    color: [#my-div color];
}

Property namespace

This is simply some syntaxic sugar. Some properties have what we could called a namespace or prefix, like font or border. These properties have many "sub" properties like font-size or border-right-color. Rather than always typing the whole property name, you can use curly braces to group them.

#my-div {
    border: {
        size: 2px;
        color: red;
        bottom: {
            size: 0px;
        }
    }
}

Will output:

#my-div {
    border-size: 2px;
    border-color: red;
    border-bottom-size: 0px;
}

Not as cool as previous features I have to say but wait for the next one.

Custom at-rules

Harmony_Style allows you to register custom at-rules. The component comes with three rules: @include, @target and @unpack. @include works like @import but the inclusion is resolved server-side. Furthermore, rules from the included stylesheet can be used in embedded queries and with inheritance in the including stylesheet.

@include url("conf.css");
#my-div {
    color: [$conf colors red];
}

@target allows you to target rules based on HTTP headers. Rules nested in the @target will be rendered only if the HTTP header match the filter. @target takes two parameters: the header's name and a regexp to match with its value. The name can be omitted. If so, the "User-Agent" header will be used. The parameters have to be placed just after the @target. The regexp must be placed between slashes. PHP modifiers can be used after the last slash.

/* will be rendered if the browser is Firefox */
@target /firefox/i {
    ul {
        list-style-type: none;
    }
}
/* will be rendered if the browser language is french */
@target Accept-Language /fr/ {
    #flag-fr {
        display: none;
    }
}

Finally the @unpack at-rule can be used to import nested rules in the global scope. It takes only one parameter, the selector of the rule to unpack. Embedded queries can be used to dynamically unpack rules.

$blue {
    div {
        background-color: blue;
    }
}
@unpack $blue;

Will output:

div {
    background-color: blue;
}

We've seen the different features provided in the language. Harmony_Style also allows you to manipulate stylesheets from PHP. The API to load stylesheets is very simple:

$stylesheet = new Harmony_Style();
$stylesheet->load('style.css');
echo $stylesheet->render();

If any error occurs, an exception will be triggered. There is also a loadCss() method to load from a string rather than a file. Both methods can take as second argument an array of parameters. These parameters can be accessed in the stylesheet using the $params constant.

#my-div {
    color: [$params color];
}
$stylesheet->load('style.css', array('color' => 'red'));

The API also provide two methods to query the stylesheet using selectors: querySelector() and querySelectorAll(). The first one returns the first match rule, the second all match rules. You can also query for properties, simply by appending them at the end of the selector. Full documentation about the API will be available with the release of Harmony. Finally, I would like to show an example of a way to use Harmony_Style: creating themes.

$blue {
    div {
        color: blue;
    }
}
$red {
    div {
        color: red;
    }
}
@unpack [$params theme];

In your php code:

$stylesheet = new Harmony_Style();
$stylesheet->load('style.css', array('theme' => $_GET['theme']));
echo $stylesheet->render();

Only rules from $red or $blue will be rendered depending on the GET parameter named theme! Harmony_Style was not part of the Harmony first preview so it's not available for download on the official website. Thus, I created an archive with all the needed files to try it. You can download it by using the link below.

Download Harmony_Style.zip

About Harmony

Hi everybody, it's been a while but I'm fairly busy these times. I would like to make a little note about Harmony Framework. The news of the first preview release has been around for some time now and I have seen some reactions. Most of them is about the usefullness of the framework. I would like to remind that  Harmony is inspired and has the same goal as GWT (Google Web Toolkit). Their goal is to translate Java to Javascript and it's a great library, very useful and helpful. I don't see why Harmony's goal should be seen differently. And I'm speaking about the goal only, I'm totally ok with the fact that some people may think it's bad written, crap and anything else. I think there is a real usefullness to Harmony. Some people appears to think that the goal is to port php applications to javascript. This is NOT it! The goal is to use php for