Developer Blog

My last post about some useful questions for a PHP interview got some attention so I decided to follow up with a few test tasks to give developers on an interview. I know some companies prefer to use them instead of questions saying that this way they can see some of the actual code and get some insight about how this particular developer approaches problem solving. Unfortunately a lot of people find these frustrating, since they they are usually time consuming and often quite boring and repetitive. Those that offer some challenge are usually deeply connected with math and therefore can be hard for people who have lots of experience in the actual web development but none in math or graph algorithms.

So here are some simple test tasks that I would suggest, I would say each of them takes under an hour to complete. I tried to make them feel new and so be more interesting to the developer who’ll be solving them.

1) Print an associative array as an ASCII table. E.g you have this array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
array(
    array(
        'Name' => 'Trixie',
        'Color' => 'Green',
        'Element' => 'Earth',
        'Likes' => 'Flowers'
        ),
    array(
        'Name' => 'Tinkerbell',
        'Element' => 'Air',
        'Likes' => 'Singning',
        'Color' => 'Blue'
        ),  
    array(
        'Element' => 'Water',
        'Likes' => 'Dancing',
        'Name' => 'Blum',
        'Color' => 'Pink'
        ),
);

And expect this output:

1
2
3
4
5
6
7
+------------+-------+---------+---------+
| Name | Color | Element | Likes |
+------------+-------+---------+---------+
| Trixie | Green | Earth | Flowers |
| Tinkerbell | Blue | Air | Singing |
| Blum | Pink | Water | Dancing |
+------------+-------+---------+---------+

The position of the elements in each subarray may vary but the keys themselves are always the same. Give extra points if the developer can make Color colum colored depending on the color name (of course you will have to specify a finite list of colors then) and if he substitues the names of the elemnts with the ASCII symbols of the elements.

Most PHP developers dont get much of a chance to work with ASCII interfaces but they see such tables a lot in MySQL for example so it might be interesting for them to try this out. Drawing such a table doesnt require any additional knowledge so it wont be that hard for anyone.

2) Split an array of numbers into a specified number of groups so that the sum of all elements in each group would be as equal as possible. E.g.

1
2
3
4
5
6
7
You have these numbers:
1,2,4,7,1,6,2,8

Lets split them into 3 groups:
8,2 = 10
7,2,1 = 10
6,4,1 = 11

There are a lot of ways of approaching this and it’s very interesting to see how a developer would do this.

3) Draw an image using GD primitives (squares, circles, lines). I promise you the developers will love you for this. Just let them go wild with their imaginations. They can draw a darts board, or a car or whatever. This will among other things showcase their inner “designer”. I’ve seen some clever developers draw some pretty complex stuff using simple algorithms and primitive figures.

4) Write unit tests for a few php classes/functions. This is a bit more boring but it will show you the experience the person had with Unit Testing and how his skill to identify bottlneck cases. The easiest version would be writing test cases for some array functions like usort(), array_reverse(), array_merge() etc.

If I think of any more fun and useful test tasks to solve, I’ll be adding them here. I’d love to hear your suggestions too =)

on 30 July 2013

Recently @serfess showed me that the aliases naming for eager loaded tables wasnt really intitive. E.g. lets say you want to load all the fairies from the database together with their home tree and a meadow that this tree grow on. You would do it like this:

1
$pixie->orm->get('fairy')->with('tree.meadow')->find_all();

The problem arises when you want to write a condition such as for example to return only those fairies that live in the trees on a ‘Sunny’ meadow. Since PHPixie was automatically assigning aliases to the joined tables the meadow table would be aliased ‘a2′ which would require you to write the condition as:

1
$pixie->orm->get('fairy')->with('tree.meadow')->where('a2.name', 'Sunny')->find_all();

Which is non intuitive at all.

This has been fixed now, the aliases are named based on the names of the actual relationhips with the ‘.’ substituted by ‘_’. In our example it would be:

1
$pixie->orm->get('fairy')->with('tree.meadow')->where('tree_meadow.name', 'Sunny')->find_all();

Which is much much better =)

on 30 July 2013

I was looking to find a way of simplifying error handling and I think I’ve found the right solution. Now instead of registering an exception handler and running execute() in index.php HTTP handling has been moved to the handle_http_request() method with simple try-catch inside of it.

A new \PHPixie\Exception\PageNotFound class has been added that will be thrown when a routing error occurs. It’s now much simpler to handle these exceptions, and there is no need in overriding the Debug class anymore.

To adjust your existing project to this new scheme you need to edit your /web/index.php file:

1
2
3
4
5
6
// /web/index.php
//Instead of this line:
$pixie->bootstrap($root)->http_request()->execute()->send_headers()->send_body();

//Use this line:
$pixie->bootstrap($root)->handle_http_request();

If you have previously extended the Debug class to handle your errors, you can remove it now, and use the handle_exception() method of the Pixie class itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// /classes/App/Pixie.php
namespace App;

class Pixie extends \PHPixie\Pixie{

    public function handle_exception($exception){
        //If its a Page Not Found error redirect the user to 404 Page
        if ($exception instanceof \PHPixie\Exception\PageNotFound){
            header('Location: /sorry/'); 
        }else{
            $http_status = "503 Service Temporarily Unavailable";
            header($_SERVER["SERVER_PROTOCOL"].' '.$http_status);
            header("Status: ".$http_status);
            echo("Sorry, something is wrong");
        }
    }
}

I hope this makes a lot more sense and will make handling exceptions a whole world easier.

on 17 July 2013

I was thinking about good questions to ask while interviewing PHP developers. Most of the ones you see on internet ask either much to specific stuff that the developer doesn’t really need to know by heart anyway (like “Which parameters does preg_replace() accept?”) or have little to do with web development at all. Some interviewers like to ask developers to complete test tasks during interview, which is in my opinion much better, but in my experience a lot of those tasks are far from what developer is actually going to do in his day-to-day work.

So here are some questions in no particular order that I would suggest asking people during an interview. I won’t post answer to most of these, since if you are interviewing someone you probably know the answers anyway.

  • How do extensions like XCache or APC speed up PHP applications?
  • What are the pros and cons of using Nginx vs Apache?
  • Your application is performing slower than you would like, how will you investigate where the bottleneck is?
    A good answer should mention using XDebug to profile the webapp
  • What new features were introduced to PHP in version 5.4? How about 5.5?
  • What are Composer class maps?
  • What are the options of making cross domain AJAX requests?
    Not really a PHP question but it shows ome more in-depth knowledge
  • What is dependency injection and why is it important?
  • Do you write tests for your application?
  • What are the downsides of using singletons and how can they be replaced?
  • What is Late Static Binding?
  • You have a MySQL database with Posts and Tags tables linked using a third Post_Tags table. Now imagine you have to create an HTML table that would have two columns: name of the post, and a comma separated list of links to individual tags. Each link looks like this TAG_NAME ( so you need tag id an name to construct it). Try making it as efficient as possible.
    The naive approach of selecting all posts and then all tags for each post would be very slow if you had hundreds of posts. A much better way to approach this would be using GROUP_CONCAT to select 3 columns from database: name of the posts, a comma separated list of tag ids and a comma separated list of tag names. Then using PHP you could explode comma separated list and costruct tag links. This question is probably best suited for developers that had some solid experience.
  • Is it possible to create a function that returns numbers from 1 to infinity that you could iterate over?
    Use of generators
  • What is hash salting and why is it important?
  • How to make variable from the current scope available in a closure (anonymous function)?

I need to make a short break now, i’ll add more questions to this list later on. Feel free to comment if you have any ideas.

on 17 July 2013

Looking at site usage statistics I can see a steady increase of the number of PHPixie users. Which is great news!

I’d really like to thank everyone who descided to give PHPixie a try. as a developer it means the whole world to me when someone is using my creation.

Larger community means faster development, early bug fixes and more people to help you with your questions. But to get more developers try out PHPixie we need to give it more exposure and make sure that the lurning curve is low.

So lets have a tutorial contest!
Yes, tutorials are the best way of spreading the word while also showing people how easy it is to get started with PHPixie. And of course the rewill be prizes: writers of the best two tutorials will receive a 50$ Amazon Gift Card ( I know it’s not that much, but it’s going to get you a few digital book downloads =3 ).

  • Write a tutorial on anything connected with PHPixie (e.g. creating a simple website, using some module, writing unit tests etc.)
  • Post it on your blog or any tutorial website (Nettuts, PHPMaster, Russian-speaking users may also post on Habrahabr, etc)
  • Put a link to your tutorial in the comments

I’ll be anouncing winners on 16th August, if a lot peope will be interested in this I’ll also increase the amount of prizes.

Why should I write a tutorial?

  • Help PHPixie grow =)
  • Maybe you’ll enjoy writing as a process.
  • You get a warm fuzzy feeling knowing that someone is using your ideas
  • Some tutorial websites pay for your tutorials, so you’ll get something regardless of whether you win or not.
  • It’s raining outside and you have nothing better to do
  • It only takes you about an hour

I hope you guys will like this idea. Feel free to leave comments if you have any suggestions.

on 16 July 2013

Two new updates have just been released. The first one is using namespaces for ORM Model table names. Basically it means that \App\Model\Forest\Fairy class would now by default use the forest_fairies table and that relationships with that table would use the forest_fairy_id foreign key. This will lead to a much more obvious connection between tables and their models.

For example it’s now much easier to set up thing like categories for posts and forums by having posts_categories and forum_categories tables and Posts\Category and Forum\Category classes.

The second addition is the support for data migrations in the Migrations Module. Basically a migration might look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
return array(
    'fairies' => array(

        '_data' => array(
            'up' => array(
                'insert' => array(
                    array('fairy_name' => 'Tinkerbell'),
                    array('fairy_name' => 'Trixie')
                ),
            ),

            'down' => array(
                'delete' => array(

                    //Same syntax as in where() Query method
                    array('fairy_name', 'Tinkerbell'),
                    array('fairy_name', 'Trixie')
                )

            )
        )
    );

Row updates are also supported, check out the updated Migration Module Tutorial for a more detailed explanation.

on 4 June 2013

ORM has been updated with support for Extensions, which are modules for the ORM Model. They can help you a lot with encapsulating pieces of model logic into classes and reusing them.
And the first Extension to arrive is the support for Nested Sets, which can be added to your Model like this:

1
2
3
4
5
6
7
namespace App\Model;

class Animal extends \PHPixie\ORM\Model{
    protected $extensions = array(
        'nested'=>'\PHPixie\ORM\Extension\Nested'
    );
}

and used like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$birds = $pixie->orm->get('animal');
$birds->name = 'Birds';
$birds->nested->prepare_append();
$birds->save();

$sparrow = $pixie->orm->get('animal');
$sparrow->name = 'Sparrow';
$sparrow->nested->prepare_append($birds);
$sparrow->save();

//Refresh the element after tree has been altered
$birds = $pixie->orm->get('animal',$birds->id);

$cuckoo = $pixie->orm->get('animal');
$cuckoo->name = 'Cuckoo';
$cuckoo->nested->prepare_append($birds);
$cuckoo->save();

$birds = $pixie->orm->get('animal',$birds->id);
//Get all birds
$birds->nested->children()->find_all();

A more detailed explanation can be found in the updated ORM Tutorial.
Hope you like it =)

on 30 May 2013

Sometimes you may need to run PHPixie from command line to perform various tasks. For example you may want to set up a cron that would tidy up your database every few hours, email you logs or calculate some statistics. To achieve this all we need is an alternative entry point cli.php. An example one would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// /cli.php
$root = __DIR__ ;
$loader = require $root.'/vendor/autoload.php';
$loader->add('', $root.'/classes/');

$pixie = new \App\Pixie();
$pixie->bootstrap($root);
$method = $argv[1];
$params = array_slice($argv,2);

$cli = new \App\CLI($pixie);

//This is to avoid default HTML error rendering
try{
    call_user_func_array(array($cli, $method), $params);
}catch(Exception $e){
    echo 'ERROR: '.$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine();
}

?>

Nw we can have an App\CLI class. First parameter to the command line will determine the method to run. Here is a small example:

1
2
3
4
5
6
7
8
9
10
11
// /classes/App/CLI.php
namespace App;
class CLI {
    public $pixie;
    public function __construct($pixie) {
        $this->pixie = $pixie;
    }
    public function is($name, $type) {
        echo("$name is a $type");
    }
}

Now we can try tunning it:

1
2
> php cli.php is Tinkerbell fairy
Tinkerbell is a fairy
on 11 May 2013

This is going to be hopefully the first part of PHP pattern series. Unfortunately a lot of programming pattern examples are usually explained in an obscured fashion and most of the time in some other programming language. Though this has improved much in the recent time, I still feel I should try my hand at explaining thims in a simple fashion.

We will start with one of the most useful patterns that is present pretty much everywhere (ironically I try to avoid it like fire in PHPixie, but I’ll explain later why), the Observer. If you have any experience with event driven programming, even using filters in WordPress, you probably will recognize and understand it almost instantly. And yes, I will use fairies as examples.

The Problem
In our forest each glade will be looked after by numeroues fairies that will do their best to keep it safe and beautiful. A lot of things may happen here, like a strong rain might fall, or hawks may come looking for pray. A class for these events may look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Event{

    //Type of the event, like 'rain', 'hawks', etc.
    protected $_type;

    //Details of the event, like the strength of the rain
    //or the amount of hawks spotted
    protected $_details;

    public function __construct($glade, $type, $details = array()){
        $this->_type = $type;
        $this->_details = $details;
    }

    public function type() {
        return $this->_type;
    }

    public function details() {
        return $this->_details;
    }

}

Additionally there are many kinds of fairies, and each can contribute in a different way. They are always observing the glade, looking for an opportunity to help and reacting to the events that occur.

1
2
3
4
5
6
7
8
9
10
11
12
<?php 
abstract class Fairy{

    protected $_name;

    public function name(){
        return $this->_name;
    }

    public abstract function react($event, $glade);

}

Before we dive into some mythology we also have to make a class for the glade itself. Being also magical it will know about which fairies can help her with any particular event type and promptly notify them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Glade{

    //An associative array, where key being the type of an event
    //and the value holding an array of fairies that would help
    protected $_fairies = array();

    //Make a fairy responsible for a particular event   
    public make_responsible ($fairy, $event_type) {

        if(!isset($this->_fairies[$event_type]))
            $this->_fairies[$event_type] = array();

        $this->_fairies[$event_type][] = $fairy;
    }

    public something_happened($event) {

        if(!isset($this->_fairies[$event->type()]))
            return;

        foreach($this->_fairies[$event->type()] as $fairy)
            $fairy->react($event, $glade);
    }

}

Now let’s look into two kinds of fairies that will inhabit the glade:

  • Sylphs – fairies of air that will use wind to ward of hawks and pollinate flowers in spring.
  • Sprites – friendly fairies that will helps flowers bloom in spring, and take care of them in autumn “`php?start_inline=1 class Sylph extends Fairy {

    public function chaseawayhawks($event, $glade) { //…some code here… }

    public function blowwindsto_pollinate($event, $glade) { //…some code here… }

    public function react($event, $glade) { if($event->type() == ‘hawks’) return $this->chaseawayhawks($event, $glade);

    1
    2
    
    if($event->type() == 'spring')
        return $this->blow_winds_to_pollinate($event, $glade);
    

    }

} ”“``php?start_inline=1 class Sprite extends Fairy {

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public function help_bloom($event, $glade) {
    //...some code here...
}

public function take_care_of_flowers($event, $glade) {
    //...some code here...
}

public function react($event, $glade) {
    if($event->type() == 'autumn')
        return $this->take_care_of_flowers($event, $glade);

    if($event->type() == 'spring')
        return $this->help_bloom($event, $glade);
}

} ”`

Of course the magical glade will also know that it doesn’t need all fairies to look after all events, so it sometimes will make a fairy do only one particular thing. Since we have everything set up now we can create a glade and add fairies to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$trixie = new Sylph('Trixie');
$tinkerbell = new Sylph('Tinkerbell');
$rosetta = new Sprite('Rosetta');
$silvermist = new Sprite('Silvermist');

$glade = new Glade();

//Trixie will both help with hawks and work in spring
$glade->make_responsible($trixie, 'hawks');
$glade->make_responsible($trixie, 'spring');

//Tinkerbell will work only on pollinating
$glade->make_responsible($tinkerbell, 'spring');

//Rosetta will help with flowers in spring and autumn
$glade->make_responsible($rosetta, 'spring');
$glade->make_responsible($rosetta, 'autumn');

//Silvermist will work only when spring comes
$glade->make_responsible($silvermist , 'spring');

//Spring is coming...
$spring = new Event('spring');
$glade->something_happened($spring);

And that’s it. Programmatically speaking we subscribed our observers (fairies) to particular events on the subject object (glade). We can pass additional data with each event too. More complex implementations would allow events to be altered while they are processed and also be cancellable. I hope you enjoyed this little tutorial and will look out for more.

Now the reeason why I personally don’t like using observers or events is because they lead to non-linear code. This pattern is best suited for developing user interfaces like writing javascript for your wesite. When you add a click event handler in jQuery you are basically using an observer, though instead of an object you subscribe closures and functions. It makes a lot of sense there, since you don’t know what the user is going to do and the whole application is non-linear.
Now if you are writing backend code in PHP there is really just a single “real user event” – HTTP request, from that point on the flow is predictable so it may be written in a linear fashion. The reason why WordPress received a lot of criticism is because every plugin could apply a filter to change some piece of output or control a point of execution. Debugging such systems is hell since filters can subscribe and unsubscribe on the fly, so at times it’s pretty hard to pinpoint which filter is messsing things up. In modern PHP frameworks events are used to patch up bad design practices, allowing the developer to pass control around different classes, calling all kinds of events. But what if one of your event handlers raises an event of it’s own? Now you are handling nested events and you might as well give up at this point. There is a way around this though: Define handlers explicitly without allowing dynamic subscription to events like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Glade{

    protected $_fairies = array();

    //We define all our fairy hadlers only during construction
    public function __construct($handlers) {

        foreach($handlers as $type=>$fairies)
            foreach($fairies as $fairy)
                $this->make_responsible($fairy, $type);
    }

    //And make this method not accessible from outside
    protected make_responsible($fairy, $event_type){
        //...rest of the code
    }
    //...rest of the code

This restricts us much more, but now we always know what is going to get executed, so we made it better. The second problem is that now we need to pass the glade object everywhere, because we don’t know when something will descide to call an event upon it, lazy developers simplify it by making Glade a singleton, or making a static method that will return a glade, thus introducing global scope to their program. And global scope is hard to test and debug. The bottomline is:

Events should only be external (like user clicks) and not internal (like please filter this piece of text). Don’t introduce global scope or you WILL regret it.

Fun fact: A Sprite is a type of a fairy that is responsible for leaves changing colors with the passing of the seasons. BFor this reason bitmaps in computer graphics are referre to as “sprites”.

P.S. I actually do like the simplicity of WordPress.

on 5 May 2013

Memcache driver has been added to the Cache module. Here is how it’s configuration should look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
return array(
    'default' => array(

        //Supprted drivers are: apc, database, file, xcache and memcache
        'driver' => 'memcache',

        //Memcached host for 'memcache' driver
        'memcached_host' => '127.0.0.1',

        //Memcached port for 'memcache' driver
        'memcached_port' => '11211',
    )
);
on 7 April 2013