Tudor Barbu's professional blog

Ramblings about software development
RSS feed

Once again I’m ashamed of my government. Disappointed and enraged at it.

And this time it’s not about spending public money on crap, increasing taxes to pay astronomic salaries to some lazy ass MPs or being generally worthless. It’s much worse!

Today Romania signed ACTA. An international agreement which is so broad in scope and so evil that makes SOPA look like a plea to save the whales.

At least I’m not the only one.The following EU countries also signed it: Austria, Belgium, Bulgaria, the Czech Republic, Denmark, Finland, France, Greece, Hungary, Iceland, Ireland, Italy, Lithuania, Latvia, Luxembourg, Malta, Poland, Portugal, Slovenia, Spain, Sweden and the UK. Same on them too.

Unlike SOPA / PIPA, ACTA was negotiated in secret. The public was deemed “too ignorant” to be involved in the talks. For the first time in modern history, democracy was left out on a global scale. If you’re unfamiliar with ACTA, just take a look at the clip below:

In a world where technological progress should be used to improve the quality of life for everyone, ACTA enslaves us all.

Cheap medicine could be banned under ACTA in order to protect the intelectual rights of big pharmaceutical companies. Under current legislation, a government in difficulty, for example facing an epidemic, if it can’t get the required medication at a reasonable price, can break patents and produce the drugs in order to save its population without fear of retaliation. Under ACTA, this will no longer be possible.

All internet traffic will be monitored in order to detect possible breaches in copyright. All confidential medical information, all the love letters sent via email, all the chat conversations in which you’re flirting with your hot co-worker, all your bank details, everything – and I do mean everything – will be scanned and recorded by your ISP.

Open source programs could be banned. Even if you’re a M$ fanboy / fangirl that only uses Winblows™, you still have to understand that the Internet runs on Linux and open source. Popular services such as Google, Facebook, Wikipedia or WordPress run on open source and the Apache web server powers 60% of all the sites on the Internet.

You might even end up in jail for posting a video from your birthday party because some copyrighted music is playing in the background.

Don’t get me wrong, I’m not a lazy-ass socialist. I truly believe in capitalism, but I also believe that everybody should have a fair chance of making a good living by hard and honest work. If legislation like ACTA gets enacted, the world will be split in the chosen few, wealthy individuals that will use legislation to kill any newcomer in their field with patents and copyright issues, an army defending them and the rest, with

Respect to Germany, the Netherlands, Estonia, Cyprus and Slovakia for not signing ACTA today. But for the rest of us, the fight is not yet lost. All international treaties have to be ratified so we can still stop this.

If you want to help, contact your representative and tell him / her that you don’t want such legislation ratified. The MPs are there to represent you and usually they tend to give in when they see their political carers threatened. If enough people contact them, they will not ratify ACTA and risk not being voted again.

Go to protests, if there are some in your area.

Do not engage in fights with the police. Do not attempt to DoS government agencies. Hacktivism is for hackers and security experts. Downloading the LOIC doesn’t make you a hacker and flooding some government website won’t help that much. And if you don’t really know what you’re doing, you’re going to get caught and thrown in jail.

I wrote yesterday an article introducing Cosmin’s blog. His most recent article is on multiple inheritance and how easy it would be to implement that into weakly typed like PHP. Just have a look at the article.

Having learned OOP in Java, I am generally against multiple inheritance. I believe that if the answer is multiple inheritance, you’re asking the wrong question. But, for “academic” reasons, I tried to implement multiple inheritance in PHP. And I came up with the following abomination.

First, create a parent class from which all classes in need of multiple inheritance extend. The parent classes will be placed in the $_parents array as strings. When the main object is instantiated, the constructor creates objects from all the parent classes. And by using __call() I’m just going to redirect method calls on the main object to the first suitable parent object. I know it sounds complicated, so long story short, just read the code! I’m a developer, not a writer!

/**
 * Abomination class implementing multiple inheritance via
 * __call magic method
 */
abstract class MultipleInheritance
{
    /**
     * List of parent classes
     *
     * @var array
     * @access protected
     */
    protected $_parents = array();    

    /**
     * List of parent objects - generated automatically
     *
     * @var array
     * @access private
     */
    private $_parentObjects = array();

    /**
     * Constructor (thank you captain Obvious)
     *
     * - init the parent objects
     *
     * @access public
     */
    public function __construct()
    {
        foreach ($this->_parents as $parentClass) {
            $this->_parentObjects []= new $parentClass();
        }
    }

    /**
     * __call magic method
     *
     * @param string $name
     * @param array $arguments
     * @access public
     * @return mixed
     */
    public function __call($name, array $arguments)
    {
        foreach ($this->_parentObjects as $object) {
            if (method_exists($object, $name)) {
                return call_user_func_array(array($object, $name), $arguments);
            }
        }

        throw new Exception('No such method: ' . $name);
    }
}

Now, some very sexist implementations of Mom and Dad classes:

class Dad
{
    /**
     * Can parallel park
     *
     * @access public
     * @return void
     */
    public function park()
    {
        echo 'Look, I can parallel park' . PHP_EOL;
    }    

    /**
     * Can ground the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by DAD' . PHP_EOL;
    }
}

class Mom
{
    protected $_parents = array('GrandMa');

    /**
     * Makes sandwiches
     *
     * @access public
     * @return void
     */
    public function makeSandwich()
    {
        echo 'Just making a sandwich' . PHP_EOL;
    }    

    /**
     * Can grounds the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by MOM' . PHP_EOL;
    }
}

…and finally the child class:

class Child extends MultipleInheritance
{
    protected $_parents = array('Dad', 'Mom');
}

Let’s try it out:

$child = new Child();
$child->park();
$child->makeSandwich();
$child->ground();

And it works. And when two parent classes have the same method – ground() in this case – the method belonging to the first encountered class is executed. And voila, multiple inheritance in PHP. Well, sort of.

Now there’s a small problem with the instanceof operator. And by small problem I mean it doesn’t work and there’s no way to fix it. The following code

if ($child instanceof Mom) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}

will always go on the “else” branch, although in my application’s logic, the Child class extends from the Mom class. And since PHP doesn’t allow overloading the operators, there’s no clean way to do this. Of course, there’s a hacky way around it, by adding an isInstanceOf() method to the MultipleInheritance class:

abstract class MultipleInheritance
{
    // ...

    /**
     * Check inheritance
     *
     * @param string $class
     * @access public
     * @return bool
     */
    public function isInstanceOf($class)
    {
        if (in_array($this->_parents, $class)) {
            return true;
        }

        foreach ($this->_parentObjects as $parent) {
            if ($parent instanceof MultipleInheritance) {
                if ($parent->isInstanceOf($class)) {
                    return true;
                }
            }
        }

        return false;
    }
}

…and using it to check inheritance:

if ($child->isInstanceOf('Mom')) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}

But the abomination is not completed yet. Because I used method_exists() instead of is_callable(), magic methods in the parent class will not be detected. To fix this, just change the code from:

if (method_exists($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}

…to…

if (is_callable($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}

…and it will work. At last, the abomination is ready. Doctor Frankenstein would be proud! Here is a gist with the entire example: https://gist.github.com/1652646.

PS: DO NOT USE MULTIPLE INHERITANCE IN REAL LIFE APPLICATIONS!

New kid on the block

Meet Cosmin. He’s my dev partner at StoreBeez. He’s a software developer who recently turned to the light side of the Force by making the switch from .NET and other M$ technologies to PHP and open source.

While he still uses Windows – which bears testimony of his former allegiance with the evil empire – he’s moving up the ladder and started a blog on PHP and other FLOSS technologies. Check him out.

SOPA blackout

Today the anti-SOPA blackout came into action. Wikipedia was partially out – users just had to hit escape before the page finishes loading or disable Javascript, Google, Reddit, 9Gag and other well trafficked sites joined the protest. Unfortunately not everybody did it, although I would have expected it, as SOPA threatens the entire industry as a whole, not just a few company. YouTube, Facebook as well as other online giants stayed on the bench. Sad!

I was curious whether GoDaddy will join the protest, after the recent scandal which forced them to withdraw their support for SOPA / PIPA. They had the decency to stay out, which is good.

And a short clip outlining why people should support SOPA.

Code refactoring

I’ve had a discussion a few days ago with a friend about core refactoring. I think that most of the problems in IT emerge from the fact that almost everybody follow to the following pattern:

- Does it compile?
- Yes, but…
- Then ship it!!! Now!

I consider code refactoring a very important step of the development process, especially when dealing with strict deadlines and short iterations. When you receive today the specs for a project and the project manager tells you that the deadline is yesterday, you don’t have the time to properly implement all the design patterns, write documentation,

Unfortunately I have seen a lot of projects where nobody bothered to refactor the code as it was deemed uneconomic – “How will we explain this to the customer? Paying twice for the same thing…” – but most of the time the customer ends up paying several times more, because the development process becomes really slow, the deliverables become extremely buggy and the number of billed hours grows exponentially.

Or I just have a lot to learn about business practices and this is the desired way of doing development :) Who knows? Because I’ve seen this happening way to often.

I came across this article yesterday. The author – who calls himself Uncle Bob – has a pretty interesting biography, but that article proves that even the best of us can come up with really weird ideas. I’m not sure if regulating software development is worst than SOPA or not.

After reading a letter from another developer which tells a story about a greedy & careless (like any other) manager who jeopardizes the life of several patients by sacrificing good practices in order to hit a deadline, “Uncle Bob” comes to the conclusion that software development should be a regulated profession. And here is where things become weird.

Who can regulate software development? Who is to say that John Doe is a good developer and James Doe a bad one!? Except the market?

And further more, how will this be done? Through academic assertion? Everyone will agree that this idea is incredibly dumb, as most industry icons don’t have college education. Here are some examples:

  • Steve Jobs (dropped out)
  • Bill Gates (dropped out)
  • Larry Ellison (dropped out twice)
  • Michael Dell (dropped out)

… just to name a few. Who can say that these people can’t work in technology because they didn’t pass some lame tests?

Or let’s just have an independent body – like the WWW Consortium – which regulates the industry. Who will fund it? I for sure am not going to pay a share of my salary to keep some boring bureaucrats in office just to tell me what I can and cannot write.

And what happens with new – yet unregulated – technologies? Can we use those? If a new framework appears, do we have to wait until it gets tested and approved? That could take years, the W3C is working on the HTML5 specs since 2004…

I agree that we all should be held accountable for our actions, but there are enough regulating bodies out there. If you’re developing medical software, then it should be clinically tested like any other medical equipment or if it’s software for cars, the bodies that issue car licenses will test it. The same for software managing nuclear power-plants or airplanes. In order to say that a nuclear reactor is safe to use, the people testing it will just have to test the software also – which I’m sure happens anyway.

If it fails, the company that wrote the software gets fined, the product is banned and the people involved get sacked. And if you get canned enough times, then nobody will hire you.

Problem solved, the profession is regulated. No bureaucracy needed!

As some of you might already know, I’m working on my latest project, StoreBeez, which is a virtual mall where independent businesses and artisans can open an online store fast and easy, without having to pay any upfront costs.

The products are also displayed on our frontpage. And since I don’t want to promote a given store – all out stores are equal – displaying the products in random order seemed like a good idea. Retrieving random results is simple, just use MySQL’s rand() function and make the queries look like:

SELECT * FROM `table` ORDER BY RAND();

Which works. Every time the user reloads the page, different results are shown. The problem arises when I’m trying to paginate. Every request means a new random order and sometimes rows get displayed multiple times – on different pages – or simply get “lost”.

The solution is to keep the same order between two consecutive requests. To do this, just pass a seed to the random number generator:

SELECT * FROM `table` ORDER BY RAND({seed});

…where {seed} is a number kept in session. This way, the order is kept between requests. Given that I use Zend Framework as my “weapon of choice”, I will post a ZF solution below:

In the controller:

$page = intval($this->_getParam('page'));
$page = $page ?: 1;

if ($page == 1) {
    $namespace = new Zend_Session_Namespace('random_key');
    $namespace->key = time();
}

$productsTable = new My_Table_Products();
$products = $productsTable->fetchPaginator();
$products->setItemCountPerPage(10)
         ->setCurrentPageNumber($page);

And in the table:

class My_Table_Products
{
    // ...

    public function fetchPaginator()
    {
        $namespace = new Zend_Session_Namespace('random_key');
        $select = $this->select()
                       ->order('RAND(' . $namespace->random_key . ')');

        $paginator = Zend_Paginator::factory($select);

        return $paginator;
    }
}

SEO, SEO, SEO. Everything today is about SEO. If your site doesn’t rank high in Google or other search engines, well, it doesn’t really matter how good it is as nobody will ever get to it. And URLs are very important in the SEO process. I’m not going to talk about friendly-urls as there are thousands of articles out there on the subject, but on a slightly different problem.

Take a look at the two friendly URLs below:

www.example.com/controller/action
www.example.com/controller/action/

For Google’s crawler, these are two different URLs. Links to one of them don’t improve the link popularity of the other. And you’ll also get a lot of “duplicate title tags” in Google’s webmaster tools. Which is not good for business. Literally!!!

The obvious solution is to just redirect all URLs that don’t end with a / caracter with a HTTP 301 Permanent Redirect. Easily done via .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]

But as soon as I did it, an old nemesis of mine came back to haunt me. The server discards the POST data when redirecting and half the site stopped working. #FAIL

After thinking on a suitable solution to redirect all the POST data without bothering the user with security alerts and against all specifications, it hit me: I don’t have to. Web crawlers don’t post data so I just need to redirect the GET requests. Easily done by adding just one more line to the .htaccess file:

RewriteCond %{REQUEST_METHOD} ^(GET)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]

Voila! The solution is up and running on StoreBeez.

StoreBeez is online!!

Finally, after two months of incredible effort, StoreBeez, the startup I was working on with 3 other friends – is…tam tam tam…online!

Written entirely in PHP on Zend Framework, with the frontend relying on jQuery, the app took around 10 weeks to complete, it’s still in beta and a bit buggy, but hey, it’s a MVP. Cosmin was in charge of the payment gateway – so if you’re experiencing problems with the payment system, it’s his fault :)

If you want to find out more about StoreBeez, click the link or watch this video:

Zend Framework 2.0

Looks promising