Codementor Events

Basics of Naming Conventions for PHP Developers

Published Dec 08, 2017
Basics of Naming Conventions for PHP Developers

In Web Development world, keeping a definite naming convention is a tough job. Every developer follows the practices he feels convenient and you may even identify the code written by a particular developer. In the field of web development we call it as the DNA of the code. But as you know, web development is not meant for a single person’s job, there is always a Team effort somewhere down the line. So it becomes necessary that you follow a specific set of naming conventions in your project or even on the whole Agency level, so that every team member can easily grasp the inners of code by simply looking at a small chunk of code and takeover the further development tasks if in any case you need to switch developers. I have seen developers feeling hesitant to touch the code of peer members just because of the differences in naming conventions.

This article highlights how to make your code beautiful and manageable by following a small set of conventions. For convenience we’ll use PHP as the example language because it is most popular web development language out there and a lot of newbies easily mess-up their code by not following conventions.

Note: Here we are covering conventions in a MVC design pattern and it should be easily followed by an intermediate level developer.

Variables:

First of all, what is a variable? A variable is what stores data. A data can be of any type, be it String, Integer, Floating point values or Boolean, Arrays. I’d even go further to say that we should follow same conventions when defining Array Keys and Database Field Names as well. It improves consistency across our whole development stack.

$first_name = “John”; // Right
$last_name = “Doe”; // Right

$n1 = “John”; // Wrong  
$n2 = “Doe”; // Wrong

$my_name = “John Doe”; // Wrong  
$my_var = “John Doe”; // Wrong

So can you guess what’s wrong with $n1, $n2, $my_name and $my_var ? One word – “Ambiguity”. Ambiguous names are the biggest reason for unreadable and ugly code. So what is “Ambiguity”? It’s simply naming a variable in a way so that you can’t guess what exactly it stores. Consider for example following snippet:

$i = “Apple iPhone 6S (32GB, Rose Gold)”; 
$p = “749.00”;
$t = “749.00”;

Can you guess in the above code, what is $t? No? Okay, let’s try following code:

$item = “Apple iPhone 6S (32GB, Rose Gold)”; 
$price = “749.00”;
$total = “749.00”;

Can you guess now? Exactly! This is how you differentiate ambiguous variables from absolute variables. Obviously the latter approach is better because it is definitive.

Constants:

Constants as the name intends are meant to store the values which don’t change throughout the program. So what kind of values are supposed to be constants? They are Database Credentials, API Keys and Mathematical constants as well. There are two types of constants you can find in PHP language – Global and Class-based.

Global constants can be defined in a common file which is included in each request of our program.

define(‘DB_HOST’, ‘localhost’); 
define(‘DB_USER’, ‘db_user’); 
define(‘DB_PASS’, ‘password$%@#’);
define(‘DB_NAME’, ‘db_app’);

See, how we’ve kept the name of constants in ALL CAPS. This is to easily differentiate between constants and variables in a program.

Note : PHP Constants don’t use the $ prefix as the variables do.

Now an example of class constants:

class Circle{  
  const PI = 3.14;
   	public function circumference($radius){ 
    	return 2 * self::PI * $radius;
  }
  public function area($radius){ 
    	return self::PI * $radius * $radius;
  }
}

When you need to use a class constant inside class itself, you use the self::CONSTANT_NAME but to use constant outside class you can simply call it by replacing self with the name of the class, e.g. Circle::PI

Class constants are targeted for contained libraries such as when integrating multiple 3rd-Party APIs since a library can have all its constants inside its classes so that they don’t get conflicted with the global constants. So suppose a class decides to use PI upto 6 precisions but you yourself are using PI upto 2 precisions, you can achieve this simply by making a global PI constant and one class-specific constant. Easy, huh! ( I know this is a stupid example, in real world you’d never need to use 2 versions of PI)

Functions:

A function is a piece of code which does a specific task. Each programming language consists of a lot of functions which do different tasks. So what conventions are mostly used in functions?

There are two of them majorly used: lowercase with underscore separators and camelcase.

Consider following two examples:

function get_name(){
  // Do something
}

function getName(){
  // Do something
}

So which one is best – I’d say none, both are equally good but we personally prefer to use the camelCase convention because for variables I prefer the underscore separations and thus using camelcase for functions give a visual ease of differentiating between a function and a variable.

But (yeah, there is a but), always keep in mind that a function should always start with a “Verb” which defines what that function is trying to do in conjunction with the name of the “Entity” being affected by this function.

getName() // Right
namesList() // Wrong
listNames() // Right
sendEmail() // Right
deleteUserById($id) // Right
connectToDatabase() // Right
databaseConnection() // Wrong
prepareOutput() // Right

See, how above examples consist of “Verb” and “Entity” in the functions and which ways are correct.

This covers the global/procedural functions, what about “Class Methods”? For those, who don’t know what is a “Class Method” – it is simply a function but inside a class, we’ll cover them in greater details in our upcoming articles. Here is how you handle the naming convention for Class Methods:

class User{ 
  public function delete($id){
    // Do something
  }
}

$user = new User();
$user->delete(2); // Delete the user with ID = 2

So I’m contradicting myself for “Class Methods” – right? Yes, there is a logical explanation for this. When you use a class, a class itself represents an “Entity” of our program so suffixing the “Entity” in a function name doesn’t make sense because it becomes self-explanatory in case of class methods.

Note : An “ Entity ” is what a program is composed of. It is a universal term and is applicable across all kind of programs. A Blog website has following entities: Articles, Authors, Topics, Tags whereas an E-commerce platform consists of following entities: Products, Categories, Orders, Manufacturers, Customers. Got the idea!

Classes:

Each class should be declared in its own file. And class names must be in “StudlyCaps”

class ModelUser{

}

Private and protected properties in a class MUST BE prefixed with a single underscore, for example:

class Circle{
  public PI = 3.14;
  private $_radius; 

  private function _calculateArea(){
    return self::PI * $_radius * $_radius;
  }
}

Parentheses:

Parenthesis are important to follow correctly. There are only two conventions for parenthesis which are widely used now-a-days. You can read more about all the styles in existence here:

K&R Style Parentheses and  Allman Parentheses.

K&R Style Parentheses:

if($a == 1){
  // do something
}

Allman Parentheses:

if($a == 1){
  // do something
}

We prefer to use K&R Style parentheses because they save one line and seem natural. But a lot of people prefer Allman parentheses. It doesn’t matter which one you prefer, they both are equally good, what matters is ensuring that you stick to the one you prefer.

Epilogue:
The key to following conventions is consistency. You MUST ensure that you stick to a particular set of conventions. A lot of agencies have developed their own coding guidelines and you can follow the ones we follow here at Hashbyte. If you wish, you can mix and mingle to create yourself a new set of conventions.

Happy Coding & Merry Christmas and A Very Happy New Year!

Discover and read more posts from Veenit Chauhan
get started
post comments3Replies
Matej
4 years ago

Nice article.

My conventions

// PHP

CONSTANT;

$meaningfully_named_variable;

while ($space = 1; $after_loop_or == $condition_name; $space += 1) {

  // used to ' += 1' instead of '++' from Python
  // it makes code consistent when using ' *= 2' or ' -= 3'
}

/**
 * Description is the only comment without slash-slash (//)
 * Also slash-slash comments are always followed by a space before content
 *
 * @param string $para Explanation
 * @param array|null $meters Optional
 *
 * @return int
 */
function verb_entity_named_function($para, $meters=null) {

  // something after empty line

  // group
  // connected
  // stuff
  // together

  // return if not void
}

class MeaningfullyNamedClass {

  public CONST_SEPARATED_FROM_VARS_WITH_EMPTY_LINE;

  public $meaningfully_named_variable;
  public $another_one_with_no_empty_lines_between;

  protected $_same_but_with_prepended_underscore;

  private $_same_again_and_separated_with_empty_lines;

  public function camelCaseForMethods {

    // something
  }

}

// Also I use 'single quotes' for most anything, except "if $variable needs to be inserted", but I also ALWAYS use <double quotes="in" html="and" i-have="no explanation for that :)" >
// As you can see, no '/>' for self closing tags in HTML5, but always in XML
// JavaScript

// Will not go into to much detail here.
// Main point is I use way more spacing in JavaScript than I do in PHP
// and no underscored_variables.
// That way I am constantly aware which program language I am in.

const lowerCamelCase;

let lowerCamelCase; // Using VSCode they're coloured differently

function lowerCamelCase( spaces, inside, all, brackets ) {

  // something
}

class PascalCase {
}

In either language all functions are in one library.php or library.js file and each class gets it’s own SameNamedFile.php etc…

Myke Black
4 years ago

According to wikipedia, Both K&R and Alleman have the opening brace on a separate line. https://en.wikipedia.org/wiki/Indentation_style

The version with the brace on the same line is the 1TBS style (one true brace style) and the one with the brace on a new line is alleman (yes I noticed the typo in the second illustration too).

When I first started doing PHP, I used the condensed style all the time because it was what I was used to when working in javascript and it produces less lines of code, but having worked on larger projects with unfamiliar code, my preference is now to use open and closing braces at the same level of indent (just makes it easier in VScode to match them up). This is also the standard for c#.

Odysseas Filippidis
5 years ago

Your Allman parenthesis illustration is wrong. I guess it is a typo. However, it was a nice read. Keep it up!