PHP Coding Standards (


Always use to delimit PHP code, not the <? ?> shorthand.

 <?php ?> 

Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

if (true) { 
   switch (condition) { 
      case 1: 
      case 2: 

You are strongly encouraged to always use curly braces even in situations where they are technically optional.

if (true) { 
   // single line stuff 

Split long if statements onto several lines keeping the question mark and the colon at the front.

if (($condition1 || $condition2) 
    && $condition3 && $condition4 
   ) { 
   //code here 

There should be one space on either side of an equals sign used to assign the return value of a function to a variable

$long_variable = foo($baz); 

The CS require lines to have a maximum length of 80 chars. It is allowed to split parameters in function calls onto several lines.

   $parameterOne, $parameterTwo, $aVeryLongParameterThree

The same applies not only for parameter variables, but also for nested function calls and for arrays.

      "foo" => "bar" 

To support readability, the equal signs may be aligned in block-related assignments:

$short     = foo($bar); 
$thelonger = foo($baz);


Class and function declarations have their opening brace on a new line:

class Foo_Bar 
function doThing() 

Function declarations follow the “K&R style”

Arguments with default values go at the end of the argument list.

function doAnotherThing($id = 0, $doAgain = false) 

include_once and require_once are statements, not functions. Parentheses should not surround the subject filename.

include_once "/file.php"; 

Post a comment

PDO Tutorials 1 – Inserting Single Row

A man's got 99 problems, used mysql_query(), now he has 100.When things are urgent, we all go with the spaghetti code. When they are not, well, some of us still do. Here comes the bad news: We shouldn’t.

If it’s about inserting records to database, most of the old tutorials go with the mysql extension functions such as mysql_connect() and/or mysql_query() which actually have been sitting at the center of the security issues, for example the most popular one: SQL injection.

Deprecated: mysql_connect()PHP’s got a lot more clear recently. As of PHP version 5.5.0, using good old mysql extension functions cause a warning that the methods are now deprecated and the one simple should use mysqli functions or PDO instead. It was a recommendation, now it became a must.

In this short tutorial series, I will try to explain how I use PDO in my OOP classes and also will share codes of a small example.

After the 5 tutorials, you’ll be able to:

  1. Insert single row
  2. Do rollback in failure cases
  3. Insert multiple rows
  4. Update multiple rows
  5. Select rows

All with PDO.

1. Inserting Single Row

There are some ways of executing SQL queries with PDO. If you have your SQL statement prepared with params bound to (not recommended), you can use PDO’s exec() function. If you want to use placeholders in your query (PDO uses either ? or :paramName) and then bind parameters (recommended), you can use PDO’s prepare(), bindParam() and execute() methods (in this order). I’ll go with the second.

Since we are going with OOP, it’s a good idea to keep the basic PDO connection code in a class like Connection.

Connection class contains a WOUF (write-once-use-forever) code so there's no need to memorise it. I know I didn't. (Btw, I just made up WOUF)
class Connection
    public function dbConnect()
        try {
            $db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE. ";charset=utf8", USER, PASS);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        } catch (Exception $e) {
            die("Connection not found. Error Code (".$e->getMessage().")");
        return $db;

In our classes, we’ll store a private variable for database connections which is an instance of the Connection class. Line 7 and 8 contains some adjustments for PDO where you can find details here. I’d recommend keeping them like this but you can find discussions on Stack Overflow and make your own decision according to your case.

Now that our connection class is ready, we can write a record function to our custom object.

In this tutorial, I have an object named Object (TY, Captain Obvious) which has two attributes: id and name. They are stored in a database table named... "table". (I like to keep things simple.)
You can find the SQL query to create DB and table and other PHP codes in the repo that I'm going to share at the end of the tutorial.

First of all, we need to create a Connection instance object in our class. Best place to create this instance variable is our class’ __constructor method.

private $db;
public function __construct() {
    // create a new PDO connection instance
    $this->db = new Connection();
    $this->db = $this->db->dbConnect();

Now let’s create the recordObject method to use this $db variable to insert our object to database. Row id will be handled by the MySQL server and auto incremented.

// Record function for object with properties set
public function recordObject() {
    // create sql query
    $sql = "INSERT INTO `table` (`name`) VALUES (?) ";
    // prepare connection with the query
    $stmt = $this->db->prepare($sql);
    // bind parameters to query
    $stmt->bindParam(1, $this->name);
    // execute the statement
    if ($stmt->execute()) {
        // if statement has success, set self id to last insert id
        $this->id = $this->db->lastInsertId();
        return true;
    } else {
        return false;

As you can see in line 4, our INSERT statement is pretty much the same with an SQL command but it has a placeholder. If I was adding two columns, I’d keep adding placeholders like (?,?). Each one is represented by index (starting from 1).

One of the coolest thing about the PDO is that it handles value types by itself. If we were to use SQL queries directly, we would need to surround our strings with quotation marks. With PDO, all we need to do is just bind the string directly and it will put those marks.

After creating the formatted SQL string, I create a variable to store the PDO statement, I also prepare it with prepare() function to bind parameters in the next step. (line 6)

Now I’m ready to bind parameters to this PDO statement. Since the index of the “name” placeholder is 1, I will bind “name” value to param 1. (line 8)

That’s it. Now we can run this query with PDO’s execute() function which returns BOOLEAN and if it is true, set our object’s id to last insert ID.

Create an index.php file to put it all together and debug.

require_once __dir__."/Object.php";

$object = new Object();
$object->name = "Hello PDO";
if ($object->recordObject()) {
    echo "New record with ID: ".$object->id;
} else {
    echo "Could not record";

Run it and you the output should be: “New record with ID: ##”

That’s it for the first tutorial. Now you can insert rows one by one (yet) to database with PDO. You can find the code of this tutorial in the Github repo.

The next tutorial will be about rolling back changes which is ultimately important in such cases that the operation might be broken at some point and some of the records are inserted/updated, the rest are not. PDO can roll back the changes from a given point and it will.

Post a comment

Aligning SKPhysicsBody Correctly with SKShapeNode

When you want to create a circle in SpriteKit, SKShapeNode is the quickest and the simplest way for it. You don’t need to create images, you can manage the size, fill colour, stroke colours etc.

However, if you want this node to involve with collisions, you may get some trouble when creating an SKPhysicsBody for that node. The creating process is similar to SKSpriteNode but the alignment of it is different.

By default, SKShapeNode anchor points begin from (0, 0) and there isn’t any property to set it as we want. When we assign a SKPhysicsBody to this node, body’s anchor is its center point so the body doesn’t cover the node correctly.

Here’s how it looks when you want to implement for SKShapeNode as you do in SKSpriteNode:


There are plenty of people who were unable to solve this issue. Yet there is one answer on SO that helped me out with this.

To work around this situation, you can create an SKSpriteNode to implement the body and an SKShapeNode as the SKSpriteNode’s child to draw the shape.

First, create an SKSpriteNode and set the width and height same with the diameter of the circle

float radius = 30.0;
SKSpriteNode *aCircle = [SKSpriteNode spriteNodeWithColor:[UIColor clearColor] size:CGSizeMake(radius * 2, radius * 2)];

Then create a circular SKPhysicsBody for the SKSpriteNode (thankfully, this is possible)

SKPhysicsBody *circleBody = [SKPhysicsBody bodyWithCircleOfRadius:radius];
[circleBody setDynamic:NO];
[circleBody setUsesPreciseCollisionDetection:YES];
[aCircle circleBody];

Here is the key part. Create a CGPathRef as an ellipse in the rect with correct center values.

CGPathRef bodyPath = CGPathCreateWithEllipseInRect(CGRectMake(-[aCircle size].width / 2, -[aCircle size].height / 2, [aCircle size].width, [aCircle size].width), nil);
SKShapeNode *circleShape = [SKShapeNode node];
[circleShape setFillColor:[UIColor redColor]];
[circleShape setLineWidth:0];
[circleShape setPath:bodyPath];
[aCircle addChild:circleShape];

Don’t forget to add the child to scene then you are done. As you can see below, the physics body now matches with the node frame correctly.


Source link of the answer:
SKPhysicsBody not as expected

Other questions about similar issues:
How to align SKPhysicsBody and SKShapeNode?
Align SKPhysicsBody with SKShapeNode
SKPhysicsBody does not work on SKShapeNode
SKshapenode is not responding to Physicsbody
how to make collisions with skshapenode circles
Keeping an SKShapeNode within the bounds of an SKSpriteNode

1 Comment

Selecting Grouped Row Count When Using MySQL GROUP BY Column

You may have been using subqueries to get how many rows were grouped when using MySQL’s GROUP BY function. There’s a little trick that helps to get this number without using subqueries, more clean and faster (when the amount of rows get higher).

Let’s assume we have a table contain folks from different cities. Like this:

folk_name   |   city_name
evren       |   ohio
steve       |   ohio
cem         |   weston
don         |   sunderland
ritchie     |   weston
ian         |   hounslow
alican      |   ohio

When we want to get only city names (distinct) from this table, we may group the data by city_name column like this:

SELECT f.* FROM `folks` f GROUP BY f.`city_name`

And the result would be:

folk_name   |   city_name
ian         |   hounslow
evren       |   ohio
don         |   sunderland
cem         |   weston

The expected behaviour of GROUP BY is to select first rows so other folks from same cities do not appear. It also orders by the GROUP BY column (ascending).

Let’s say we want to get how many folks exist in each city by grouping by. First thing comes to mind could be using a subquery like this:

SELECT f1.*, (SELECT COUNT(f2.`folk_name`) FROM `folks` f2 WHERE f2.`city_name` = f1.`city_name`) AS `folk_count` FROM `folks` f1 GROUP BY `city_name`

And the result would be:

folk_name   |   city_name   |   folk_count
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Let’s admit, subqueries are messy. They make the query more complicated to read and also are question marks on performance.

How about selecting number 1 (one) for each row and sum it up on grouping by?

Doing something like this:

SELECT f.*,SUM(1) AS `folk_count` FROM `folks` f GROUP BY f.`city_name`

Would return:

folk_name   |   city_name   |   folk_count
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Nicely done.

Post a comment

DateTime Ticks With Objective-C

If you need to generate unique strings for every case, the concept of DateTime.Ticks is probably the best solution for you. It represents the count of seconds since the oldest DateTime object available.

However, DateTime.Ticks usage comes from .NET platform and it is that easy in .NET, not in Objective-C.

To generate a ticks number in Objective-C, you need to do the following:

  1. Create an NSDate (01.01.0001), I know, rocking.
  2. Calculate the ticks between this oldest date and [NSDate date] (which means now).
  3. Turn that double variable to an integer. Well, long integer. Or… long long integer. (True story).

Here’s how I did it:

// Create the date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];

// Create the oldest day possible
NSDate *ticksDate = [dateFormat dateFromString:@"00010101"];

// Get ticks difference between now and 01.01.0001 in double    
double ticksDouble = [[NSDate date] timeIntervalSinceDate:ticksDate];

// Turn it to a long long int
long long int ticks = llround(ticksDouble);

// Test it
Post a comment

How to Install Git 1.8.x || Upgrade Git to 1.8.x


You don’t get surprised when you see that your CentOS, Ubuntu or another server already has Git installed. However, the default Git version that comes with the OS bundle is usually v1.7.1 and this might be a problem when you want to install applications which require higher Git versions(For example, Gitlab).

This article contains the steps that I followed while installing(or upgrading to) Git to a CentOS 6.4 server.

First of all, make sure if you have git installed:

which git

This has to return a value like “/usr/local/bin/git”. If it doesn’t, than you don’t have Git installed on your machine.

If it does return a path, than you better know which version, by using this command:

git --version

The result should be like: “git version 1.7.1”. If it returns the number equals or higher than the version you want to install, well, you got lucky. The day is over for you.

OK, let’s begin with a new installation.

1. Go to /tmp folder:

cd /tmp

(Those who have older version of Git installed may go to step 3.)

2. Install default version of Git and maker for installing git:

yum -y install git perl-ExtUtils-MakeMaker

3. Clone git repo to your /tmp folder:

git clone git://

4. Get inside of the repo and checkout your favorite version. I chose v1.8.3.4, you may choose something else.

cd /tmp/git/
git checkout v1.8.3.4

5. Continue preparing installation:

./configure --prefix=/usr/local

IMPORTANT: You might have got an error like “-bash: ./configure: Permission denied”. If you haven’t, continue with step 7. If you have, no need to worry, we’ll fix it by using these commands:
6. Fix “Permission denied” error if exist

mount -o remount,exec,suid /tmp
mount -o remount,exec,suid /var/tmp

7. Do it

make && make install

8. Cleanup

rm -rf /tmp/git/

9. Verify your installation:

which git

(Should return Git path like “/usr/local/bin/git”)

10. Verify your version

git --version

(Should return your version, like: “git version”)

You may find most of the steps above in various websites, however it really took me a while to find out how to fix the permission error which I declared in step 6.

Fair enough, let’s go make some fork!

Post a comment