phpBeanstalkdAdmin

phpBeanstalkdAdmin is a monitoring and administration interface for Beanstalkd.

PHP-DI

PHP-DI is a dependency injection framework for PHP.

Overriding dependencies with Composer

At my company, My C-Sense, we use Doctrine amongst other PHP frameworks and libraries. When we find bugs (or need new features), we contribute to the project through our open source initiative.

The problem is when we submit a pull request on Github, several months usually happen until our fix appears in a stable release.

To be able to enjoy our bugfixes immediately, here is our workflow:

  • We fork the repository of the project to our organization account
  • We commit and publish the bugfix in a branch of our repository
  • We submit a Pull Request
  • We override the dependency to the project with our version in Composer

Overriding a dependency is quite simple: just add your git repository in your composer.json and require you branch.

But when we want to override, for example, doctrine/common which is used by doctrine/orm, then we have a problem: doctrine/orm wants a stable version of doctrine/common, it will conflict with your requirement to a dev branch.

The solution is to alias your dev branch to a stable release, and that is possible through the awesome “inline alias” functionality in Composer.

Here is an example:

{
    "require": {
        "doctrine/orm": "2.3.*",
        "doctrine/common": "dev-ChainDriverFix as 2.3.0"
    },
    "repositories": [
        {
            "type": "git",
            "url": "https://github.com/myclabs/common.git"
        }
    ]
}

Here, our branch ChainDriverFix will override the 2.3.0 version of doctrine/common, which will also be compatible with doctrine/orm!

Programming jokes of the week end

Every developer knows this joke:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

I can’t help but share the great serie that I read on twitter tonight:

The “Optional Singleton” pattern

The singleton is a practical design pattern, that’s the reason it is so popular amongst beginners. It is also an anti-pattern because of the problems it introduces (global state, difficult to test, …).

While I agree with that, and the fact that Singletons should be used with (a lot of) moderation, I also like an alternative pattern which comes with the advantage of the singleton and balances out its disadvantages. This can be useful if you have to work on a codebase that has singletons.

I’m calling this pattern the Optional Singleton for lack of a better name.

Simply put, this is a class which you can use as a singleton, or not (it’s optional ;):

  • you can still use the handy MySingleton::getInstance()
  • you can however create new instances of the class, for example for tests

Read more ›

jQuery plugin: Confirm dialogs for HTML links and buttons

This is the first open source project created at my company, so I am quite proud of it even though it is not much.

The name is jquery.confirm, which is pretty explicit. It lets you have confirmation dialogs for links or buttons. For example, “Are you sure you want to delete that comment?” kind of things.

I am going to present its basic usage and options here.

The idea is to write unobtrusive Javascript by letting the user write clean HTML:

<a href="home" class="confirm">Go to home</a>

To enable confirmation on this link, simply:

$(".confirm").confirm();

That will show a confirmation dialog each time the user clicks the link. If the user confirms, the plugin will then redirect him to the link.

You can configure the texts and labels through the options. You can also change the actions that are executed when the user confirms (follow the link) or cancels (do nothing), so you can perform AJAX requests for example.

One interesting option is to force the link to be called with a POST request instead of a GET:

$(".confirm").confirm({
    post: true
});

On your server-side code, you can check that the request is POST and refuse GET request. That can help prevent security issues like someone sending a link to delete someone else’s account for example: http://example.com/my-account/delete. If you only accept POST request, people clicking on that link won’t see their account deleted (because the request would be a GET).

If you want to learn more or try it, the website contains the official documentation and some demos.

Be a better programmer: take a step back

Replace [client] by [boss] or anything of the kind if you prefer.

A day at work

Bug #3890 from Client

There is an application crash, it says “division by zero error in SpeedCalculator::compute()”.

Please fix ASAP!

You open SpeedCalculator.php to find:

public function compute() {
    return $this->distance / $this->time;
}

Read more ›

Doctrine schema validation in a PHPUnit test

Doctrine offers a command line option to validate the schema (or mapping):

./doctrine orm:validate-schema

This is very useful, when I ran it against my code, which was working by the way, I got several errors/warnings.

However, I didn’t want to have to run this tool manually once in a while. I already have tests for that. So I thought: why not integrating the schema validation to the tests!

Read more ›

Introduction to Dependency Injection with a real life example

This example is an introduction to the Dependency Injection concept. It is based on the PHP library PHP-DI.

Classic implementation

Given you have:

class GoogleMapsService {
    public function getCoordinatesFromAddress($address) {
        // calls Google Maps webservice
    }
}
class OpenStreetMapService {
    public function getCoordinatesFromAddress($address) {
        // calls OpenStreetMap webservice
    }
}

The classic way of doing things is:

class StoreService {
    public function getStoreCoordinates($store) {
        $geolocationService = new GoogleMapsService();
        // or $geolocationService = GoogleMapsService::getInstance() if you use singletons
        return $geolocationService->getCoordinatesFromAddress($store->getAddress());
    }
}

Now we want to use the OpenStreetMapService instead of GoogleMapsService, how do we do? We have to change the code of StoreService, and all the other classes that use GoogleMapsService.

Without dependency injection, your classes are tightly coupled with their dependencies.

Read more ›

The PHP-FIG should define PHP interfaces

Bouncing on the discussion initiated in the #52 ticket of the PHP-FIG project on Github: « Explain the scope of the PSR system », I’ll explain the case I’m trying to make.

First, PHP-FIG, which stands for Framework Interoperability Group, is a gathering of major PHP frameworks and project who try to:

to talk about the commonalities between our projects and find ways we can work together.

This group has released PSR-0, PSR-1 and PSR-2, three specifications of coding standards, guide style and code organisation (for autoloading interoperability). Now the question is asked: is it the role of the PHP-FIG to define technical “code” specifications or is it out of its scope? Here is my answer.

PSR-0/1-2 are contracts between its users to ensure cohesiveness and compatibility.

Think of the PSR-0 for example, it enabled all projects to be compatible regarding class autoloading. To achieve this, no code or PHP interface was necessary because what the autoloading needed was only file names, directories and class names constraints.

Now there are other questions that need standardization for interoperability between PHP projects. And some of them need PHP interfaces.

For example, PHP (or the SPL) does not define a Collection interface (or any implementation). However, a Collection is a base object, and I bet it is used (or could be used) in many projects. Now Doctrine defined their own Collection interface (because it needed it) and I’m sure other projects did the same for the same reasons, but that situation is stupid. A Collection is a standard data structure, implementations may vary but the Collection interface should be defined once and for all.

And PHP interfaces are contracts between its users to ensure cohesiveness and compatibility.

Notice any similarity between PSR-0/1/2 and interfaces. They are the same thing, applied to different things. They are technical specifications.

I agree that the SPL was a good start and maybe would have been a good place for such things, but it is a still project, with no big changes lately, a lot of inertia and several big lacks (and who decides what’s in the SPL?). The PHP FIG is the perfect group to bring a solution to this: it is active, dynamic, open and transparent, representative of the major PHP projects, and it has the competences and the momentum to make it useful and used (that will not be “yet another PHP library”, it will be used by major frameworks).

If PHP-FIG doesn’t do it, then who will (and more importantly: who will make it a success)?

And to extend my point, have a look on the Java side (JSR), and for example JSR-107 which defines interfaces for cache API, or JSR-220 which defines JPA (specification of persistence API that Doctrine 2 has followed).

TL/DR: I think PHP-FIG should define and provide PHP interfaces. PHP-FIG defines technical specifications for interoperability between PHP projects. PHP interfaces are a form of technical specifications, they can allow PHP projects to be more compatible and work better together. PHP-FIG is the best group possible to standardize classic/mainstream API (utility classes, …). Java does it, it works, that should inspire us.

Doctrine 2 YAML reference

If you are working with Doctrine 2 and its YAML configuration files for the object mapping, you may find the documentation lacking some details.

Here is a gist of all the YAML syntax possible:

Read more ›

Dependency Injection with PHP

I used to develop using Singletons, registries or even static classes. Those days are gone.

I decided to use Dependency Injection so that:

  • my classes would be testable
  • replacing an implementation by another would be not only doable, but easy (and so extending a library/module would too)
  • the design of those classes wouldn’t be guided by the question of “how they will be used”
  • my code would be cleaner, simpler
  • and IDE auto-completion/type-hinting would always work

I gave a try to Symfony and ZF2 DI systems, but they both seem way too complicated for just a simple need (that anyone who has worked with Spring would understand):

class MyClass {
    /**
     * @Inject
     * @var MyService
     */
    private $service;
}

This short code means: Inject, using a simple annotation, an instance of another class into a property.

I started working on a framework enabling such functionality few months ago. It is now in a mature state. It is based on the Annotations library of Doctrine 2, and takes most of its ideas of Spring 3.

You can check out this framework on its official website: PHP-DI, and you are welcome to use it or contribute.