Categories
Uncategorized

My experience with PHP/Zend certification

This post has been sitting in my drafts since 2013. I figured it was time to finish and publish it.

I passed PHP Certification exam. It felt nice. I had read about how people failed more than once so it was cool that I passed it on my first try.

Registering for the test

I’m sure there’s more than one way to do it but I went to Zend’s website and bought an exam voucher, which was $195. They have various packages where they offer to give you a crash course or study material and such but I decided to study on my own.

When you buy the voucher Zend will send you an email with the voucher code. You will, then, have to register with Pearson Vue on http://pearsonvue.com/ for the test. Provide them the voucher code Zend gave you. Then, you can pick a date when you want to take the test, and take it.

After buying the voucher you have a year to use it before it expires. You can set an exam date that’s more than year away as long as you register for the test within the year on buying the voucher. My voucher was going to expire in November 2011 so I registered for the test one day before the expiration date and set the exam date to Jan 2012.

Preparing for the exam

The exam isn’t super hard but it’s not something you can pass without preparing for it. And, it looked like the people designing the questions put effort into it.

  • Download the Zend Certification Study Guide from their website and read it
  • Go to php.net and read up on all functions related to strings, arrays, streams, the standard PHP library
  • I would recommend taking mock exams if you can get them. It will give you an idea about what type of questions to expect

Does getting the certification do anything for your career?

A lot of times, recruiters confuse Zend certification with , being certified for the Zend framework. Surprisingly, more than PHP certification, people have asked if I was certified for Zend framework.

The certification definitely helps give recruiters some confidence in hiring you over another developer but I wouldn’t say it catapulted my career to new heights. When I did the certification, I got a free perpetual license for Zend Studio which was nice. I, however, decided to ditch the free license and pay for PHPStorm.

Should you take the test?

I would say, yes. I studied for it for a little over a month and discovered gems of knowledge I probably wouldn’t have found otherwise. Taking the test and passing was a great experience for me.

So, if you can spare a few hundred dollars and put in some studying, I say go for it.

Here are some sample questions similar to what you might see in the PHP certification exam:

Which of the following cannot be used to set a cookie

  • setcookie
  • $_COOKIE
  • setrawcookie
  • header

What is the output of the following code

<?php

try {
    class MyCustomException extends Exception {}
    try {
        throw new MyCustomException();
    } catch (Exception $e) {
        print '1:';
        throw $e;
    } catch (MyCustomException $e1) {
        print '2:';
        throw $e1;
    }
} catch (Exception $e) {
print get_class($e);
}

Which of the following can be used to traverse the file system:

  • ArrayObject
  • RecursiveDirectoryIterator
  • SplTmpFileInfo
  • TraversingIterator

How often will func() run?

function func(&x=0, &y=1)
{
if ($x > $y) {
return;
}
$r = $x + $y;
$x = $y;
$y = $r;
}

func()

Categories
Islam

Oaths in Islam – Part 2

Since I posted an article on “Oaths in Islam”, I have gotten quite a few questions from readers (most of which I have not published) asking me to clarify if an oath they took is valid or something else related to oaths they took. I figured I would write another article providing examples to help such people out.

First I’d like to state that I am not a scholar, or even a formal student of sacred knowledge. I just happen to like learning and get my knowledge from reading various books, articles and listening to lectures. I had written the original article as a reminder for me after having read articles about oaths on sunnipath.com (now qibla.com) and other sources. Here is the original article, I am talking about: http://moazzam-khan.com/oaths-in-islam/ if you are curious.

My friend/whoever took an oath that they will do something bad to themselves if I don’t do what they want.

If your friend, or anyone else takes an oath to not eat (or harm themselves) until you do something, that is between them. You are not responsible for their oaths. If they break those oaths, they will have to pay kaffarah for it. It doesn’t affect you. No one can force you to do something by taking an oath. Allah will not hold you accountable for an oath someone else took.

I swore that I will not let my son/daughter do something (like play soccer), but I want to let them play it. What should I do?

Firstly, try not to take oaths you can’t keep. Secondly, if you break your oath, you will have to pay the kaffarah. If you don’t break that oath, then you son/daughter will not get to play soccer (or whatever you forbade them from) .

Categories
Uncategorized

3D Printing

The future is here – with 3D printing. If anyone has seen Star Trek, they will know about the synthesizer used in the show to make (synthesize) anything from coffee to costumes to anything else. This is how I felt when I first got my 3D printer and started making (printing) things with it.

You can pretty much design and print anything. It is, however, not as fast as the ones on the show (or the movies). They take a while to print somethhing but they are precise and will make almost anything you want/need. I have printed a holder for dry-erase markers and cleaning spray (which turned out to be better than anything I have ever bought for it), green latern rings for the kids, toy cars and many other things. It is also not as expensive as I thought it would be. To be fair, there are printers out there that cost upwards of $10,000 but they are not meant for a hobby-ist.

I got my printer for (I am not kidding) $250 on a sale. It’s regular price is $300 (Monoprice maker select v2).The plastic it uses to print stuff cost me $14.00 and will print things that cost a lot more than that.I printed a car phone ring holder. Each ring holder in the store costs $20. I printed it for less than a dollar.

I will try and post pictures of things I have printed in another post and my experiences with my printer and 3D printing in general.

Categories
Go

Why Golang/Go is so awesome

I have been working with Go for quite some time now and know more about it. My initial thoughts about it were accurate, I think with some variations. Go really can do almost everything.

It can be run like any interpreted language for development and compiled for production

This is something I love about Go a lot. You can run any Go code by just typing:

go run someFile.go

And, you can compile your whole app into a binary, copy that binary to a production server and just run it. No dependencies needed. If you have assets that your app reads (like images, etc) , they can be compiled into the binary as well! This gives a whole new meaning to portability (at least for me).

It supports parallelism and concurrency

With Go routines, you can run multiple things at the same time (assuming you have a multi-core CPU). Go takes care of splitting your routines into multiple-threads and all the house-keeping chores that come along with it. It is, by far, the best multi-threaded language I have come across.

Many developers think Node supports parallelism but it doesn’t. Node is a great language for its asynchronous model but it executes only 1 thread at a time. Most scripting languages that I know of (Ruby, Python, etc) have this issue. They have a global interpreter lock, which makes sure only one thread executes at a time. So, they are concurrent but do not support parallelism (running multiple things at the same time).

Since, web servers spawns multiple processes for processing multiple HTTP requests, you don’t generally notice the bottleneck.

It has a unit testing framework in its standard library

It’s the first language, I’ve seen doing this. No need to install external libraries. The testing framework (in a package called “testing”) is very performant. It also lets you run benchmark tests and example code for generating documentation.

It has support for GUIs apps

There are a bunch of libraries in Go that will let you write native applications for Windows, Mac, etc. Go has bindings for GTK, QML, etc. Some Go libraries will even let you write hybrid apps (for desktop applications – will talk about mobile later).The content in these native UIs can be done using HTML/CSS. I tried this for a proof-of-concept app that generates configuration for a proprietary ETL tool at my work and it is so easy to do! The library I used was : https://github.com/murlokswarm/app

It has support for writing web services and web applications

Go, with it’s standard library has a templating engine built-in. And, it is very performant. No need to worry about which library to use for templating, etc. You can, with a few lines of code, create a web service!

There are quite a few features that make Go a great language to work with. I hope it proliferates the IT market so much that more companies ask for Go as a main requirement for jobs (and not just a nice-to-have).

Categories
Go

Golang: Restart web server on file change

A great feature of scripting languages like PHP, Python and Ruby is that you don’t need to re-compile the app or restart a web server every time you change something. With Go, you need to restart the web server for your changes to take affect. This can be a pretty daunting task.

We can, however, have this feature in Go as well (with some extra code). We just need to write a file watcher that will restart the web server on any file changes. Below is working code (from a project I am building) that does exactly this. You can modify it to suit your needs or just put it in your project as is.

package main

// This file is: web/main_dev.go
// It will recursively monitor any path we are interested in and re-start the web server
// on any file changes
//
// web/main.go is where my web server code resides. You should change the code
// to your run the command you use for your web server in main() 

import (
    "os/exec"
    "path/filepath"
    "os"
    "crypto/md5"
    "io"
    "encoding/hex"
    "time"
    "fmt"
)

// We will store all MD5 hashes of files we are interested in, in this variable
var fileHashes map[string]string

// Command to start the web server
var cmd *exec.Cmd

// Path we want to monitor for file changes
var pathToMonitor string

// fileMd5 calculates the md5 hash of a file
// Source obtained from http://www.mrwaggel.be/post/generate-md5-hash-of-a-file/
func fileMd5(filePath string) (string, error) {
    //Initialize variable returnMD5String now in case an error has to be returned
    var returnMD5String string

    //Open the passed argument and check for any error
    file, err := os.Open(filePath)
    if err != nil {
        return returnMD5String, err
    }

    //Tell the program to call the following function when the current function returns
    defer file.Close()

    //Open a new hash interface to write to
    hash := md5.New()

    //Copy the file in the hash interface and check for any error
    if _, err := io.Copy(hash, file); err != nil {
        return returnMD5String, err
    }

    //Get the 16 bytes hash
    hashInBytes := hash.Sum(nil)[:16]

    //Convert the bytes to a string
    returnMD5String = hex.EncodeToString(hashInBytes)

    return returnMD5String, nil

}

// fileWatcher monitors files and restarts the web server if any file changes
func fileWatcher() {
    for {
        filepath.Walk(pathToMonitor, func(path string, f os.FileInfo, err error) error {
            fileHash, err := fileMd5(path)
            if err != nil {
                //panic(`Could not calculate hash for ` + path)
            }

            if _, ok := fileHashes[path]; !ok {
                fileHashes[path], _ = fileMd5(path)

            } else if fileHashes[path] != fileHash {
                fileHashes[path] = fileHash

                fmt.Println(`file changed`, path, ` . Restarting web server`)
                cmd.Process.Kill()
                cmd.Run()
            }

            return nil
        })

        time.Sleep(100)
    }
}

func main() {
    pathToMonitor = "./"

    // First we get MD5 hashes of all the files we want to monitor
    fileHashes = make(map[string]string)
    filepath.Walk(pathToMonitor, func(path string, f os.FileInfo, err error) error {
        fileHashes[path], _ = fileMd5(path)


        return nil
    })



    // Start a file watcher go rountine that will monitor the files for
    // any changes
    go fileWatcher()

    // Run the web server
    fmt.Println(`Started server`)
    cmd = exec.Command(`go`, `run`, `web/main.go`)
    cmd.Run()

    // Create a channel and wait on it. This is here so the main thread
    // exit
    doneChannel := make(chan bool)
    _ = <- doneChannel
}
    
Categories
Go

Golang: Get the function caller’s name

Problem

Consider this code:

package main 

import "fmt"

func foo() {
    // foo() wants to know who called it
    fmt.Println("HI")
}

func main() {
    foo()
}

In the function foo, we want to get the name of the function (and preferably file name and number ) that called it.

Solution

We can get this information by traversing the stack trace (which Go’s “runtime” package has handy functions for:

func foo() {
    fpcs := make([]uintptr, 1)
    // Skip 2 levels to get the caller
    n := runtime.Callers(2, fpcs)
    if n == 0 {
        fmt.Println("MSG: NO CALLER")
    }

    caller := runtime.FuncForPC(fpcs[0]-1)
    if caller == nil {
        fmt.Println("MSG CALLER WAS NIL")
    }

    // Print the file name and line number
    fmt.Println(caller.FileLine(fpcs[0]-1))

    // Print the name of the function
    fmt.Println(caller.Name())
}
Categories
Go

Golang: Connect to Postgres and selecting data from a table

You will need to get the Postgres driver first. In the terminal type:

go get github.com/lib/pq

Connecting to Postgres

package main

import (
    _ "github.com/lib/pq"
    "database/sql"
    "fmt"
)

func main() {
    // Connect to the DB, panic if failed
    db, err := sql.Open("postgres", "postgres://user:[email protected]/dbName?sslmode=disable")
    if err != nil {
        fmt.Println(`Could not connect to db`)
        panic(err)
    }
    defer db.Close()
}

Selecting data from a table

After connecting to the database, you can do the following:

rows, err := db.Query(`SELECT * FROM table WHERE name=$1`, `Moz`)
if err != nil {
    panic(err)
}

var col1 string
var col2 string
for rows.Next() {
    rows.Scan(&col1, &col2)
    fmt.Println(col1, col2)
}
Categories
Uncategorized

Earn more by learning Go!

According to this article a friend forwarded to me, software developers who learn Go, Python or Scala (along with tech like Apache Spark) have found it easier to find jobs with better salaries. Learning Scala caused the highest boost and in the second place was Go.

Learning python is a bit subjective in terms of getting a raise. It depends on what you are doing and which field you are in. So the increase in income with Python isn’t as consistent as it is with the other 2 languages.

Here is the article in detail: http://www.infoworld.com/article/3071623/salary/want-to-boost-your-salary-learn-scala-golang-or-python.html

Categories
Uncategorized

Golang: Testing HTTP requests

Unit testing HTTP calls to external services is pretty easy in Go. Let’s say we have some code that makes HTTP requests like so:

package something

import (
    "net/http"
)

func SomeFunc(url) string {
    rs, _ := http.Get(url)
    defer rs.Body.Close()
    body, _ := ioutil.ReadAll(rs)

    return string(body)   
}

We can test if the request is made and we get the response we want by mocking the external service. Below is the code:

package something

import (
    "net/http/httptest"
)

/**
This code uses Ginkgo and Gomega for unit tests but this can be easily adopted to any other framework or vanilla Go tests
**/
var _ = Describe("It makes HTTP requests", func () {
    Context("In some context", func () {
        It("makes an HTTP response which returns something", func() {
            server := httptest.NewServer(http.HandlerFunc(func(rs http.ResponseWriter, rq *http.Request) {
                if rq.RequestURI == `/` {
                    content := "Hello"
                    if err != nil {
                        fmt.Println("FL", err)
                    }
                    rs.Write(content)
                }
            }))
            defer server.Close()

            // If we were testing for the response, we do assert it.  
            Expect(someFunc(server.URL)).To(Equal("Hello")
        }
    })
})
Categories
Uncategorized

Golang: Make HTTP requests

A simple GET request can be made like this:

package main

import (
    "net/http"
    "ioutil"
)

func main() {
    // Make a get request
    rs, err := http.Get("https://google.com")
    // Process response
    if err != nil {
        panic(err) // More idiomatic way would be to print the error and die unless it's a serious error
    }
    defer rs.Body.Close()

    bodyBytes, err := ioutil.ReadAll(rs.Body)
    if err != nil {
        panic(err)
    }

    bodyString := string(bodyBytes)
}

POST request:

import (
    "bytes"
)
func main() {
    body := []byte("key1=val1&key2=val2")
    rs, err := http.Post("http://someurl.com", "body/type", bytes.NewBuffer(body))
    // Code to process response (written in Get request snippet) goes here

    // Simulating a form post is done like this:
    rs, err := http.PostForm("http://example.com/form",
                            url.Values{"key": {"Value"}, "id": {"123"}})
    // Code to process response (written in Get request snippet) goes here
}

If more control is needed, like specifying headers, cookies, etc:

// ...
client := &http.Client{}
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Add("If-None-Match", `some value`)
resp, err := client.Do(req)
// Code to process response