Simple CakePHP REST API application

I’ve got a task to create simple WebService which communicates over REST API with another applications. The whole idea behind is to have 2 applications

  1. Application which will provide information via REST API
  2. Application which will communicate with first one and present data to the end user

Believe or not, CakePHP can handle both applications.

WebService REST API

Simple REST application to return data about user. The application responses in JSON / XML style. Demo WS Application

Web Application

Simple Web Application which communicates with REST Application running on by using JSON / XML. Demo Application.

Pretty easy :).

SOLVED: PHPStorm – FTP: Could not list the contents of folder

I had a problem with FTP connection in my PHPStorm application. Each time I was trying to login to the remote server, I could see the content of all the folders there except public_html. So I could not upload directly from the IDE. This annoyed me quite a lot.


I was searching and most of the manuals / helps were saying to tick Passive mode in Advance Options for my server. Unfortunately this didn’t help me. After another 15 minutes I came across a help saying, that I have to tick also Always use LIST command. I followed the instruction and the problem became part of my history :D.

I was wrong – PHP IDE is useful

Couple of months ago I had a discussion with friend of mine about IDE like PHPStorm or Eclipse and simple tools like Sublime Text. I was telling him, that as PHP Developer – Sublime Text is fair enough for me and the IDE should be use by Java Developers or C++ Developers. But I didn’t see the point of using it for PHP development. I know all my classes, Sublime makes it easy to open new file by pressing Ctrl+P which gives you an extra easy way how to find whatever file you are looking for. Sublime came with great features which I used on daily basics etc.

So the questions for me was – do I really need a PHP IDE for my job? How I will learn all new hot-keys again – that’s always my biggest worry. Will the IDE give me some help with CakePHP applications? I made some research and I decided to try PHPStorm – not because it’s done by czech company ;).

After one month of using this tool, I must say I felt in love with it. It speeds up my ever day job and it gives me almost all the features that I had in Sublime Text. But the greatest thing is, that PHPStorm is fully customizable – so I could map my hot-keys from Sublime Text to do exactly same job in PHPStorm.

I’m going to use this for most of my development tasks from now on.

PHPUnit + CakePHP + PhpStorm 8

PHPStorm is a great IDE which I use everyday together with our platform build over CakePHP Framework.  CakePHP comes with his own CakeUnit Test, which is an extension of PHPUnit and makes unit testing even more easier.

If you need to enable CakePHP2 Unit Test in your PHPStorm IDE, I’d recommend to follow instructions presented here: Running CakePHP2 Unit Tests in PhpStorm.

If you are using PHPStorm 8.x, you must make a modification into cakeunit4phpstorm.php file.

// Just simply replace handleArguments(array $argv) function by this one 
protected function handleArguments(array $argv)

    $printer = null;
    if (isset($this->arguments['printer'])) {
        $printer = $this->arguments['printer'];
    $printer = new IDE_PHPUnit_TextUI_ResultPrinter($printer);
    $this->arguments['printer'] = $printer;
    $this->arguments['listeners'][] = new IDE_PHPUnit_Framework_TestListener($printer);

That’s all what you have to do and you can start enjoying unit testing in CakePHP.

PHP Operator precedence with example

I came across interesting issue during last days. I was ask to solve following task.

$a = 2;
$b = 3;
$c = 0;

if($a || $b & $c) {
    echo 'first ';

if($a || $b && $c) {
    echo 'second ';

if($a || $b AND $c) {
    echo 'third ';

Question 1: What will be the output?

The output of script above will be: first second

Question 2: Why?

The first two are very trivial. They will pass because $a = 2 so the rest of the condition will be forgotten.

The interesting part comes with conditions number 3. To be honest, I have seen this style maybe only once in my life during all my years of development. But this is exactly a good example for interview.

The solution is hidden in Operator precedence in PHP . Operators &, &&, || have much more priority than AND, OR. So PHP would transform the condition to this:

if($a || $b) {
    if($c) {
        return true;
    } else {
        return false;
} else {
    return false;

I hope it’s clear now and I hope no-one can trick you again ;)

PHP Snake game – will a snake survive?

I was put in front of this task:

Probably all of us remember a game called Snake, where you have to eat as many apples as you can. As you may guess your task is to write a program which determines whether our snake wins the game or it ends up eating itself. Snake moves along an infinitely large board. It can turn left, right or go straight. Also, the snake – when going straight – can eat an apple under condition it is in front of him. If such a scenario occurs our friend extends onto a cell where the meal took place. The initial snake length is 1.

For each test you should print YES if the snake survives the whole game without dying or otherwise print number of the step in which the snake bites itself.

PHP Code

Sample code

require_once './bootstrap.php';
use \Ptx\Snake;

$snake_obj = new Snake();
$moves_2_test = [

foreach($moves_2_test as $move) {
    try {
        $result = $snake_obj->move_snake($move);

        echo $move . ': ';
        echo ($result == -1) ? 'YES' : $result;
        echo "\r\n";
    } catch(\Ptx\SnakeException $e) {
        echo $e->getMessage();

Console application

We can also play this game by using PHP Cli (php from command line)

$ php snake.php FLERFF
Welcome to snake 1.0
F - Forward
L - Left
R - Right
E - Forward & Eat

FLERFF: Survived

Considered Notable by

Today I’ve got an email from saying, that the code was considered notable by them.
Notable packages are carefully hand picked by a site moderator. The moderator that picked your package wrote the following comment:

“Interesting PHP class that can simulate the moves of the snake game to determine if the snake would survive.”

Difference array_merge vs + in PHP with example

+ (plus)

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. 


If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Example 1

$boys = ['tomas', 'henry', 'george'];
$girls = ['therese', 'ladia', 'lisa'];

$family = $boys + $girls; 
$family_2 = array_merge($boys, $girls);

// var_dump($family)
    [0] => 'tomas',
    [1] => 'henry',
    [2] => 'george'

// var_dump($family_2)
    [0] => 'tomas',
    [1] => 'henry',
    [2] => 'george',
    [3] => 'therese', 
    [4] => 'ladia',
    [5] => 'lisa'

Example 2

$array = ['tomas' => 1, 'therese' => 2, 'henry' => 3];
$array_2 = [4,'tomas' => 5,6];

$group_1 = $array + $array_2;
$group_2 = array_merge($array, $array_2);

// var_dump($group_1)
    [tomas] => 1
    [therese] => 2
    [henry] => 3
    [0] => 4
    [1] => 6

// var_dump($group_2) 
    [tomas] => 5 
    [therese] => 2
    [henry] => 3
    [0] => 4
    [1] => 6

Difference between self::$var and static::$var in PHP?

I had an interview recently and I was asked to explain exactly same question as the title of the article.

The difference is very easy – it’s for late static bindings introduced in PHP 5.3.

Let’s have a look on example below

class Foo {
    protected static $var = 'I am the Foo class';

    public static function get_var() {
        return self::$var;

class Bar extends Foo {
    protected static $var = 'I am the Bar class';

Before PHP 5.3
Imagine calling echo Bar::get_var() – it will print ‘I am the Foo class’ even though we might have expected string’I am the Bar class’ printed.

Late static binding
Late static binding solves the problem. What we have to do it so update our code little bit to following:

class Foo {
    protected static $var = 'I am the Foo class';

    public static function get_var() {
        return static::$var;

class Bar extends Foo {
    protected static $var = 'I am the Bar class';

No, if we call echo Bar::get_var() would end up with our expected string ‘I am the Bar class';

How to assertContains 2 arrays in PHPUnit

Last night I was writing some unit tests for one of my application and I wanted to check whether return array contains my expected array. I needed it mostly for comparing data which comes from database after insert / update action.

I tried to search little bit, but I could not find any solution. So from the fact of being PHP Developer, I wrote my own test function. Let’s see it on an example:

1. I have a function which adds row status => 1 when status key is missing

function complete_data(array $data) {
    if(!array_key_exists('status', $data)) {
        $data['status'] = 1;

    return $data;

2. Let’s write an unit test to check it

class AppTest extends PHPUnit_Framework_TestCase {


    function testCompleteData() {
        $data = array(
            'id' => null, 
            'name' => 'Test');
        $complete_data = complete_data($data);

        $expected_data = array(
            'id' => null,
            'name' => 'Test',
            'status' => 1);

        $this->assertTrue($this->_assert_contains_array($expected_data, $complete_data));



3. We need a function to compare these two arrays

 * Compare Arrays contains
 * simple function which compares 2 arrays whether $expected in part of $returned
 * @param array $expected - array which was expected
 * @param array $return - array which was returned
 * @return boolean
protected function _assert_contains_array($expected, $returned) {
    foreach($expected as $key => $value) {
        if(is_array($value)) {
            if(array_key_exists($key, $returned)) {
                return $this->_compare_arrays_contains($expected[$key], $returned[$key]);
            } else {
                return false;
        } else {
            if(!array_key_exists($key, $returned)) {
                return false;
            } else if($value != $returned[$key]) {
                return false;

    return true;

And we are done, the test will pass and my job is done. Just a note – function _assert_contains_array works also great with multi-dimensional arrays.

PHP Developer or PHP Programmer

Last couple of days I’ve spent with playing around my website. And the first thing I wanted to changes it its title. So if someone looks for Tomas Pavlatka in Google – e.g. some HR person – I want him to get immediately idea, who I am.

So my two choices were

  1. Tomas Pavlatka – passionate PHP Developer
  2. Tomas Pavlatka – passionate PHP Programmer

I didn’t know which of these two I should choose. So I asked Google to give me a help hand. Let’s check some comparisons:

1. Google Search
When I search for PHP Developer in Google, Google tells me he knows about 160 000 000 pages for it.
Google Search for PHP Develoeper

On the other hand, when I search for PHP Programmer in Google, Google knows only about 19 000 000 pages.
Google Search for PHP Programmer

2. Keyword Planner
Another great tool to make this comparison is Keyword Planner offered by Google Adwords. Let’s see what it can tell us about PHP Developer vs. PHP Programmer fight.

Let’s start with PHP Developer – the average monthly search volume is 9.900.
Google Keyword Planner - PHP Developer

If I use the same tool to find information about PHP Programmer, it tells me about only 1.300 average monthly searches.

Based on the results above, I can clearly see that PHP Developer is more used than PHP Programmer. It doesn’t actually mean it’s better to use PHP Developer – if you are doing SEO, because it might be very difficult to get on good position in Google. But because my aim is not to be the first one in Google on phrase PHP Developer, I will use it as so many people use it as well.

© 2015 Tomas Pavlatka

Theme by Anders NorenUp ↑