Monday, June 30, 2014

PHP has lambda function! :D

I just discovered that you can perform lambda function with PHP tonight! Here's how to do it:

# First, go to php console  (you will need to install HipHop)

php -a


Welcome to HipHop Debugger!
Type "help" or "?" for a complete list of commands.

Note: no server specified, debugging local scripts only.
If you want to connect to a server, launch with "-h" or use:
  [m]achine [c]onnect <servername>

hphpd> 

# mapper function in PHP is called "array_map", it takes in a function and an array, just like Python:
$result = array_map( $a==> $a+1, [1,2,3,4])

$a ==> $a+1    is a lambda function, where $a is each element in the array. The function simply takes the value and plus one. the $result is expected to have [2,3,4,5]

$result will be another array of numbers.

To get an array of values from the $result variable, we need to do something similar to .to_a method in Ruby:

var_dump($result)

array(4) {
  [0]=>
  int(2)
  [1]=>
  int(3)
  [2]=>
  int(4)
  [3]=>
  int(5)

}

The result is as expected.

Tuesday, June 24, 2014

Power up my PHP site with Hip-hop!

Finally I made up my mind, and decide to try out Hiphop as a replacement for PHP5.

The installation was very straight-forward. I installed following the tutorial:

 http://fideloper.com/hhvm-nginx-laravel#comment-1325788095

In short:

$ sudo add-apt-repository -y ppa:mapnik/boost
$ wget -O - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-key add -
$ echo deb http://dl.hhvm.com/ubuntu precise main | sudo tee /etc/apt/sources.list.d/hhvm.list
$ sudo apt-get update
$ sudo apt-get install -y hhvm
$ sudo update-rc.d hhvm defaults

# Restart the service now
$ sudo service hhvm restart                      # We'll also restart HHVM
and inside my nginx config: /etc/nginx/sites-available/default, added one line "include hhvm.conf"

... Stuff above this omitted ...
    # Make site accessible from http://localhost/
    server_name localhost;
    include hhvm.conf;  # HERE'S THE MAGIC

    location / {
... Stuff below this omitted ...
Restarted now my site is running on Hip-hop! The performance improvement is significant. The requests per second increased about 5 times without any logic update! :D

(Some remaining issue: as my site is running on Laravel 3, I had to adjust some of the library to make it. Mostly 2 parts: Laravel 3 defined "yield" as a function for blade template engine, which is a reserved word in Hip-Hop. And Hip-hop came with its own Redis client, having a name clash with the Redis client from Laravel 3. If you ran into similar trouble, here is a diff patch to apply to make it compatible:

https://gist.github.com/yuhanz/afc6189330ce0c6120a8

If you have an old PHP site and are lazy about rewriting it, it is a good option to go with Hip-hop. They supports various PHP frameworks:

http://hhvm.com/frameworks/