Recent Comments
Archives
Visitors
  • 44886This month:
  • 1292Today:
  • 16Currently online:



LeaseWeb CDN

Posts Tagged ‘php’

How to win a senior programmer job interview

This post will give you 3 advices that will help you to win any job interview for a senior programmer position. It does not matter that you can’t program when asked during the interview, just follow these simple advices and you are one step closer to being a rockstar software developer earning big bucks!

Advice 1: Learn the Fizzbuzz answer

Most interviewers ask the same question to measure programming skills: program Fizzbuzz. It is a very popular, but extremely tricky assignment that even the most skilled programmers fail at. Just learn the code in the required language by hearth and you will fool any interviewer. Note that you really don’t have to understand the code as the explanation of what the code does is given in the assignment.

Java implementation (Fizzbuzz)

public class FizzBuzz {
	public static void main(String[] args) {
		for (int i = 1; i <= 100; i++) {
			if (i % 15 == 0) {
				System.out.println("FizzBuzz");
			} else if (i % 3 == 0) {
				System.out.println("Fizz");
			} else if (i % 5 == 0) {
				System.out.println("Buzz");
			} else {
				System.out.println(i);
			}
		}
	}
}

PHP implementation (Fizzbuzz)

<?php
for ($i = 1; $i <= 100; $i++)
{
    if (!($i % 15))
        echo "FizzBuzz\n";
    elseif (!($i % 3))
        echo "Fizz\n";
    elseif (!($i % 5))
        echo "Buzz\n";
    else
        echo "$i\n";
}

Python implementation (Fizzbuzz)

for i in xrange(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i

C implementation (Fizzbuzz)

#include <stdio.h>

int main (void)
{
    int i;
    for (i = 1; i <= 100; i++)
    {
        if (!(i % 15))
            printf ("FizzBuzz");
        else if (!(i % 3))
            printf ("Fizz");
        else if (!(i % 5))
            printf ("Buzz");
        else
            printf ("%d", i);

        printf("\n");
    }
    return 0;
}

Advice 2: Learn the “100 to 1″ answer

A very smart interviewer has come up with an alternative to the popular FizzBuzz assignment called “100 to 1“. Probably because the FizzBuzz answers got really easy to Google. The assignment is to print a count down from 100 to 1 using a “for” loop that has a loop variable “i” that starts at 0. This blog has gotten exclusive access to the secret answers to this very hard and brand new assignment. Use them in your benefit!

Java implementation (100 to 1)

public class HundredToOne {
	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			System.out.println(100-i);
		}
	}
}

PHP implementation (100 to 1)

<?php
for ($i = 0; $i < 100; $i++)
{
    echo (100-$i)."\n";
}

Python implementation (100 to 1)

for i in xrange(0, 100):
    print 100-i

C implementation (100 to 1)

#include <stdio.h>

int main (void)
{
    int i;
    for (i = 0; i < 100; i++)
    {
        printf ("%d\n", 100-i);
    }
    return 0;
}

Advice 3: Failure defense and contract extension

If you make a mistake, then don’t worry. Claim it is due to test anxiety. Another great defense is that you could not solve it, because you rely heavily on your favorite IDE. If that does not work, then you can say that the assignment seemed so trivial to you that you could not believe it was the actual assignment and you were looking for the hidden “difficulty”. One of these will work every time, guaranteed!

Some people have commented that they are worried about being outed as an impostor as soon as they won the job. Don’t be! By the time you are “up to speed” you are already earning big bucks for a few months and you have passed your trial period. Also, by posing humble, showing your effort and indicating that you are having trouble “adapting to the working environment” or “finding your spot in the team” you can probably achieve to win a contract extension.

Conclusion

It is important to realize that you can become good at winning a senior programmer job and also that being a great programmer is not always the easiest way to win it. Be aware that there may be some luck involved as not every interviewer asks the right questions (the ones above) or is sensible enough to buy your defenses (if you even need these). Don’t be discouraged if you do not succeed at once. There are enough companies eager to hire senior programmers, so you can have many chances as they interview anyone who sends them an impressive CV.

Let me know if it worked for you! Or maybe don’t… as I would become really depressed if it did (as this is a satirical post). ūüėČ

Chef server API integration with PHP

In this post I will show you a quick example of how you can integrate with the chef server api from php.

If you don’t know chef I recommend to have a look at https://www.chef.io. Chef is a configuration management tool, similar to ansible or puppet.

Chef turns infrastructure into code. With Chef, you can automate how you build, deploy, and manage your infrastructure.

At LeaseWeb our infrastructure that supports our business consists of many machines. For us it was a logical step to use a configuration management tool to manage all those servers and we chose chef. We also use chef to automate most of our (web) application deployments.

While our “chef managed” infrastructure was getting bigger, deploying fixes and features got easier and more frequent we needed something so our organisation is able to know what is being deployed and when.

Php is the main language we use here and we use Guzzle for quick and easy integration with rest api’s and web services.

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

Read more about guzzle here http://guzzle.readthedocs.org/.

We have created a plugin for Guzzle3 that implements the chef server authentication algorithm as described in their documentation https://docs.chef.io/auth.html

The plugin can be found on our github page https://github.com/LeaseWeb/chefauth-guzzle-plugin.

The plugin takes care of adding all the necessary http headers and signing the request to make a fully authenticated call to the chef server.

To start consuming the chef server rest api either checkout the source code with git or add the plugin as a dependency to your project using `composer`:

    php composer.phar require "leaseweb/chef-guzzle-plugin":"1.0.0"

Once you have created a user in chef the two things you need to get started is the client name of this user (in this example we assume my-dashboard) and the private key of this client (in this example we assume it is stored in my-dashboard.pem):

    <?php

    use Guzzle\Http\Client;
    use LeaseWeb\ChefGuzzle\Plugin\ChefAuth\ChefAuthPlugin;

    // Supply your client name and location of the private key.
    $chefAuthPlugin = new ChefAuthPlugin("my-dashboard", "my-dashboard.pem");

    // Create a new guzzle client
    $client = new Client('https://manage.opscode.com');
    $client->addSubscriber($chefAuthPlugin);

    // Now you can make calls to the chef server
    $response = $client->get('/organizations/my-organization/nodes')->send();

    $nodes = $response->json();

There is a ton of things you can do with the chef api, read more about it here https://docs.chef.io/api_chef_server.html

Hopefully this plugin will make it easier to integrate your chef’ed infrastructure in your company processes.

We are playing around with:

  • automatically generating release notes for our applications,
  • automatically update our issue tracking systems after a chef deployment
  • and many more.

How to mock MySQLi when unit testing with PHPUnit

PHPUnit is the most used unit testing framework for PHP. Today I wanted to unit test some PHP code that relies on MySQLi. The dilemma is that you either need an actual database and load a fixture or you need to mock the database. As Claudio Lasalla clearly puts:

Unit tests are not “unit” tests if they test things other than the System Under Test (SUT).

And further explains:

Unit tests check on the behavior of units. Think of a class as being a unit. Classes, more often than not, have external dependencies. Tests for such classes should not use their real dependencies because if the dependencies have defects, the tests fail, even though the code inside the class may be perfectly fine.

This theory made total sense to me. That’s why I decided to mock the MySQLi dependency. In this post I will show you just how far I came before I realized this was not going to work out (for me).

The code

The test class, that extends “PHPUnit Framework TestCase”, has an extra method “expectQueries()”. The class looks like this:

<?php

class MySQL_CRUD_API_Test extends PHPUnit_Framework_TestCase
{
	private function expectQueries($queries)
	{
		$mysqli = $this->getMockBuilder('mysqli')
			->setMethods(array('query','real_escape_string'))
			->getMock();
		$mysqli->expects($this->any())
			->method('real_escape_string')
			->will($this->returnCallback(function($str) { return addslashes($str); }));
		$mysqli->expects($this->any())
			->method('query')
			->will($this->returnCallback(function($query) use ($queries) {
				$this->assertTrue(isset($queries[$query]));
				$results = $queries[$query];
				$mysqli_result = $this->getMockBuilder('mysqli_result')
					->setMethods(array('fetch_row','close'))
					->disableOriginalConstructor()
					->getMock();
				$mysqli_result->expects($this->any())
					->method('fetch_row')
					->will($this->returnCallback(function() use ($results) {
						static $r = 0;
						return isset($results[$r])?$results[$r++]:false;
					}));
				return $mysqli_result;
			}));

		return $mysqli;
	}

	public function testSomeSubjectThatUsesMysqli()
	{
		$mysqli = $this->expectQueries(array(
			"SELECT * FROM `table`" =>array(array('1','value1'),array('2','value2'),array('3','value3')),
			"SELECT * FROM `table` LIMIT 2" =>array(array('1','value1'),array('2','value2')),
			// other queries that may be called
		));
		// do something that uses $mysqli
	}
}

The subject-under-test is actually doing something like this:

$result = $mysqli->query("SELECT * FROM `table`");
while ($row = $result->fetch_row()) {
	// do something with the data in $row
}
$result->close();

And in the test it will return the corresponding rows for the queries that you execute. Nice huh?

Not ready

This is a proof-of-concept of a mock of the MySQLi component for PHPUnit. The ‘real_escape_string’ function has a sloppy implementation. It does not (yet) support the much used ‘prepare’, ‘execute’ or ‘fetch_fields’ methods. To give an idea of the completeness, for MySQLi it now support 2/62 functions and properties, for MySQLi Statement 0/28 and for MySQLi Result 2/15. Apart from this incompleteness there is the problem that you may need to support meta information, such as field names and types, to have a fully working mock. If you feel like continuing my work, then feel free to take my code.

Conclusion

Although this was a nice exercise and it may even be the right thing to do in theory, it did not seem to make much sense (to me) in practice. So I gave up on this approach and my current implementation runs all tests against a real database. It loads a database from a SQL file (fixture) in the static ‘setUpBeforeClass()’ function. This may not be so ‘correct’ or ‘clean’ (from a unit testing point of view), but it is much faster to write and easier to maintain.

My question for you: Am I wrong or is the theory wrong? Please tell me using the comments.

MindaPHP now has Memcache support

The PHP framework I am building (MindaPHP) already contains support for MySQL and cURL. Today I have added Memcache support. Memcache can be used for two main purposes in PHP: session storage and application caching. In the framework we only support debugging Memcache for application caching. This is how the debugger looks when the Cache class is used:

mindaphp_cache

The cache is used to store the results from the Bing query. You can try this on: http://maurits.server.nlware.com/hello/bing (click the debugger link in the bottom bar after searching).

Memcache for application caching

Now you can speed up your application using the following commands:

$var = Cache::get($key)
$success = Cache::set($key,$var,$expire=0)
$success = Cache::delete($key)
$success = Cache::add($key,$var,$expire=0)
$success = Cache::replace($key,$var,$expire=0)
$var = Cache::increment($key,$value=1)
$var = Cache::decrement($key,$value=1)

The commands “get” and “set” do retrieval and storage of values in the cache based on the “key” parameter. The commands “add” and “replace” are comparable to “set”, but either fail when the key does (in case of add) or does not (in case of replace) exist. The “increment” and “decrement” commands can be used for counters, but beware that “increment” fails when the key does not exist. This is why you may want to call “add” before you increment.

Memcache for session storage

If you want to use Memcache for session storage in PHP (with any framework), you configured this in “php.ini” with the following statements:

session.save_handler = memcache
session.save_path = "tcp://localhost:11211"

Note that you need the Memcache daemon and the php Memcache extension installed. The following command installs the required software on a Debian based Linux (like Ubuntu):

sudo apt-get install php5-memcache memcached

Have fun accelerating you application!

MySQL-CRUD-API now supports SQL Server 2012

Although the project was initially aimed at only providing support for MySQL, now MS SQL Server 2012 is also supported. MySQL-CRUD-API is a single PHP file that will provide a full REST API for your data structure. With the now added SQLSRV-CRUD-API class you can also connect to a SQL Server database. This only works if the SQLSRV driver is installed in PHP and this is only available for Windows.

sql_server

The SQL Server code relies on the “OFFSET” command, which was added to SQL Server in version 2012. It also allows for UTF-8 character encoding, IMHO a character set any modern database should use. The offset command was added by popular demand (to SQL Server), because the pagination in SQL Server was quite cumbersome, especially when compared to MySQL. Now they are on par again. Also the choice of the SQLSRV driver over the more compatible, but inferior, FreeTDS driver was intentional.

SELECT * FROM [posts] ORDER BY [published] DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

The response on this project has been mostly positive. There are people arguing that it is bad to expose the data structure of your database. My counter argument is that if you do proper database administration (data management) this is not true. And in that case you do not need all that boilerplate code that APIs generally consist of as it can all be automated. That is this project’s philosophy.

https://github.com/mevdschee/mysql-crud-api

Check out the code on Github and tell me what you think. Use the comments for feedback.