Keeping it clean: Coding standards that matter

Posted by love.huria on Jun 19, 2017 6:16:00 PM

A year back, I was working on a project that taught me how to keep my code clean, modular, reusable, and all those terms that seem fancy, but are actually good for you in the long run. Interesting? Yeah a bit.
But what did I do after getting into those practices?
I made mistakes. Believe me, a lot of them. But with every mistake, I learnt a lot of stuff that I had never considered before. It helped me in my thinking process, on how we should build things, what steps we need to consider when we are developing/extending a feature. And most importantly, these learnings were not just personally helpful, but also crucial for team growth.
At first we used to get frustrated because we had to follow the additional steps like adding documentation, maintaining changelog files, following the code standards, and keeping them consistent throughout the team. These extra steps seemed cumbersome and we were not able to relate how this can be helpful for the team. And we are still learning/improving everyday in this respect. But after few months we started loving and improvising the process. 
So here I am, sharing what I have learnt. And trust me when I say this, once you start doing these, you can't code without following these practices.

This post is focused on what practices we follow everyday to make our lives easier. Although the practices mentioned here are more relatable for PHP/Drupal, they can be easily followed by all developers.
Let’s start off with simple things:

Commenting and Documentation Standards

Commenting doesn’t mean adding a bunch of comments and random documentation anywhere while coding. There are things which you should mention to make your colleagues’ lives easier, and yours as well. 

  • Start with writing a description of your component, why you are creating it, and what is the aim you would like to accomplish here, what does it do etc.
  • If there are modifications being done, then those should be logged by creating a file attached to your component. Maintain a specific format to have consistency throughout. 

This is something we follow at Srijan, hope this is pretty clear: file sample: 


  • It’s good practice to add @see, referencing the class, which will help easily navigate to that class definition by using IDE like PHPStorm, or editors like Sublime etc with just one click.

new 2


  • Add @TODOS wherever necessary. It’s very important if you feel your code can be improved in future and you have the ideas on how to do it, but not enough time at the moment. Mention what needs to be improved above that code snippet. One good example could be:

new 3

  • Create files so that others can easily understand what is the working of the module. 

          For example: 

new 4

  • A “Docblock” is a special code comment that offers an explanation of the purpose, arguments, return values, and throw exceptions for a block of code. 


Something very informative in a simple tweet I found:


This might include indenting, whitespace, brace positions, and new lines and this can be different according to different languages. In our case, this is specific to PHP (Drupal). There are a lot of plugins available in editors to beautify your code.

Naming Conventions

  • Of course naming conventions depend on the language you are using ( examples: Zend, Google style guides for PHP, CSS, Javascript, Java, etc ) but the main idea is to use descriptive and meaningful words. So, you should avoid calling your variables: xx, yy2, test1, test2 and so on.

  • For example, lower_case for PHP variables and functions, camelCase for JS variables and functions, lower-case-hyphenated for CSS ID's and classes, UPPER_CASE for constants.

  • We should name our variables in a way which easily explains the type of data they contain. Similarly in case of functions, they should describe what kind of functionality they are providing. This is called self-documenting code. Functions should tell what they do, not how. This is called abstraction which allows the underlying implementation to be changed without changing the function name.


Keep your code as loosely coupled as possible. It is "portable" in that the amount of work required to move it from one platform to another is low. There are few things we should have in mind while coding:

  • Avoid using hardcoded values like absolute file paths, URLs etc  unless it’s a matter of life and death (:P)
  • Avoid using magic numbers in your code. Basically it’s a hard-coded value that may change at a later stage, and hence become hard to update. Almost all numbers other than 0, 1 or 2 should be assigned to a constant at the top of the file. This provides a single point of change if the value changes, rather than a search-and-replace that could affect many files and potentially introduce bugs.


There are different types of tools available to find syntactic discrepancies in general, especially in interpreted languages like JavaScript, PHP, Python etc. They can also be used as simple debuggers for finding common errors. Here’s a look at the common linters we use at Srijan:

PHP: We use PHP Code Sniffer with Drupal integration. One can easily configure it with your editors such as Sublime which will show common PHP errors on save, which saves a lot of time and prevents errors before committing your changes. 

Javascript: We have

  • We have Drupal JavaScript coding standards (note - these vary in several ways from Mavericks standards) in place but we use JSHint for listing our JS related code checks. 
  • Wherever Drupal's JS formatting conventions conflict with JSHint, JSHint supersedes. 


  • We do not have any SCSS related documentation on but we do have Drupal CSS coding standards (these can be applied to SCSS code).
  • You can find some documentation related to SCSSLint here.
  • Also it’s good to checkout Compass best practices as well. 


This is something we are working on quite extensively. We are building reusable components which can be used in across different websites (which have almost the same purpose). These components will provide the basic functionality and styles which can be overridden in different websites according to their own requirements. The most important thing here is to identify what functionality can be turned into a component.The degree to which your code is reusable is largely based on how tightly it’s coupled with the rest of your code base. A good example can be building a banner slider which can be used in most of the websites.


This basically means keeping your code independent of others, so that one bad change to your code does not break everything else. This is similar to the concept of coupling in object oriented programming. It’s like breaking the website into its basic independent parts of a more manageable size.

Use Continuous Integration Tools

We use Travis CI. It’s a distributed continuous integration service used to build and test projects on github. The service is free for open source projects. You  might be wondering why you didn’t you use it before! ? Don’t worry, It’s never too late and pretty easy to setup with your github repositories.

  • First step is to register Travis-CI, which you can also do with your github account.
  • Setup the .travis.yml file, This file handles the build of your environment and also the execution of the phpunit files.

You can check the simplest basic configuration here:


When you have the phpunit test in place and if it is passed, it will show something like this on your commit:


Simple Travis setup:

  • This .travis.yml should be at the root of the project.
  • Travis only runs builds on the commits you push after you’ve enabled the repository in Travis CI.

Code Reviews

We have pretty awesome code review process in place. But this blog is already too long, so I shall cover that in my next blog. Stay tuned. 

Meanwhile, you can check out our webinar by Elijah Manor, on how to sniff out JavaScript code errors.

Topics: Drupal, Coding and Tutorial

How to Parse JSON Data from a REST API using simple JSON Library

Posted by Nilanjana on Apr 15, 2016 4:11:00 PM

Let’s start by understanding what is a JSON based API. JSON (Java Script Object Notation) is a lightweight data interchange format that is now being used as a profound and efficient way of gathering, collecting or sharing data among applications and interfaces. JSON provides data to its corresponding calling function in key, value pairs. ‘Key’ as in the variable and ‘value’ as in the corresponding value for the variable. The data that is parsed from a JSON API is in the form of object which needs to be converted into their respective data format as acceptable by the system.


I won’t go into much details into describing API’s in this blog post( may be in my upcoming one). REST (REpresentational State Transfer) is an architectural style and is an approach to communicate between different modules that is often used in the development of web services. So in this blog I would describe how can you use JAVA to leverage JSON data from a REST API.

Before starting, here is the REST API I am using to parse data into my system JSON-API.

Now what is the use of parsing JSON data from a web service when I can have it in my system already ? The answer to this would be, now a days maximum of the client data is available over the web as it is not prone to data loss.  Moreover clients built around JSON API are able to take advantage of its features around efficiently caching responses, sometimes eliminating network requests entirely. So let’s proceed ahead and I would try to explain the process of parsing the data.


Pass the desired URL as an object. So that would be likePass the desired URL as an object. So that would be like


Type cast the URL object into a HttpURLConnection object. The benefit of doing it is that we would be able to harness the properties of the HttpURLConnection class to validate features. For example set the request type or check the status of the response code.Type cast the URL object into a HttpURLConnection object


Set the request type as in whether the request to the API is a GET request or a POST request. Set the request type as in whether the request to the API is a GET request or a POST request.  


Open a connection stream to the corresponding API.Open a connection stream to the corresponding API.  


Get the corresponding response code.Get the corresponding response code.  


Now I need to perform a check that if response code is not 200 then throw a runtime exception otherwise carry on the rest of the procedure. So the structure would be

 perform a check that if response code is not 200 then throw a runtime exception otherwise carry on the rest of the procedure.


I have used the method scanner to read each line from the API and fetch the data in string format. Now this part is inside else { } that I mentioned above.

method scanner to read each line from the API and fetch the data in string format.

method scanner to read each line from the API and fetch the data in string format.

So the parsed data would something like this

Now you have all the data with you from the API. But somehow it looks a bit unstructured and definitely rather than the whole data you would need it categorically. So for this you need to parse this data into JSON object. In some cases you need to store the data in JSON array as well.

JAVA by default does not have any inbuilt class or provide any inbuilt class, method to parse and store these data as objects. So, for that you need the classJSONObject (to store the corresponding string data as JSON objects), JSONArray (to hold JSON objects in an array) and JSONParser (to convert string object into JSON objects). For that you will need a package called SimpleJSON. Download the required jar files and configure its class path in the system.


Declare an instance of the JSONParser

Declare an instance of the JSONParser


Convert the string objects into JSON objects.

JSONObject jobj = (JSONObject)parse.parse(inline);

So if you view the JSON structure which would be something like this

 Convert the string objects into JSON objects. JSONObject jobj = (JSONObject)parse.parse(inline); So if you view the JSON structure which would be something like this

I would now like to get the corresponding values under the results array. So here how you do it:


First convert the JSON object into JSONArray object like this

 First convert the JSON object into JSONArray object like this  


Once the JSON objects are stored in the array, read the corresponding JSONArray objects, convert it to JSON objects again. So you get the elements within the results array. So here is how you do it.
Once the JSON objects are stored in the array, read the corresponding JSONArray objects, convert it to JSON objects again. So you get the elements within the results array. So here is how you do it.


Once the JSON objects are stored in the array, read the corresponding JSONArray objects, convert it to JSON objects again. So you get the elements within the results array. So here is how you do it.

Once the JSON objects are stored in the array, read the corresponding JSONArray objects, convert it to JSON objects again. So you get the elements within the results array. So here is how you do it.

Let’s us dig a bit deeper. Suppose I want the components of “address_components”. Here is the JSON structure

So how would I get the components under the address_components array? Follow the same step as above

That's all I have about the subject, for more resources you can lookup the git hub link to help you out with Parsing Data from JSON REST API.

Topics: API Management, Coding and Tutorial

Building layouts from 7 to 8: Coding vs Clicking

Posted by Nilanjana on Sep 25, 2015 3:34:00 PM

osef Dabernig and Adam Juran delivered an interesting session at DrupalCon Barcelona on transition of building layouts from Drupal 7 to Drupal 8. 

They start with a review of the existing Drupal 7 contrib solutions like Context, Display Suite and Panels. You’ll get good insights into their status and equivalent frameworks in Drupal 8.


So which approach do you take to build layouts in Drupal? 

Josef and Adam give a good overview of the two main approaches:

1. Coding -If you’re a front-end developer, you will most probably prefer this approach.

Leave the PHP to the back end guys!
 Clicking - That’s what site builders do. Display suite or Panels are very powerful tools indeed.
2. Clicking - That’s what site builders do. Display suite or Panels are very powerful tools indeed.

Yes, click all the things!

Watch the session of how you can build a simple layout, a landing page and a layout with variations using the 2 approaches mentioned above.
You’ll also see what’s new in Drupal 8 and how it compares to the options available in Drupal 7.

Topics: Drupal, User Experience and User Interface, Coding and Tutorial

How to implement Facet Search on data in Drupal 7

Posted by Nilanjana on Sep 3, 2015 4:33:00 PM

If you are thinking about creating a website where you can show your big data, then with the help of facet search your website user can actually find specific data related to them. In this blog, I will help you in setting up Facet search functionality on your data in Drupal 7. 

The Faceted Search module provides a search API and a search interface for allowing users to browse content in such a way that they can rapidly get acquainted with the scope and nature of the content, and never get lost in the data. More than a search interface, this is an information navigation and discovery tool.

In order to make such functionality, you need to install some modules on your site. We will first make an  Indexing engine which will index all your data, and then we will make blocks of specific data which will allow you to filter all the related data to itself.

Modules to install for implementing Facet Search:

  1. Facet API
  2. Search API
  3. Database search
  4. Search Facets
  5. Search Views
  6. Entity API

Now that we are done with installing and enabling above modules, follow the below steps. Steps to follow:


  1. Create the content type and add fields in respective content type.

  2. Configure the search server

  3. configure the search index

  4. Add fields on in Facet API

  5. Create a complete view  of your data

Each step is explained below

Step 1. Create content type and add fields in that:

Let’s take an example that we created content type

  • Title: Company

  • Fields: Address

  • Fields: County

Now create content of above content type and add data into it.

Right now we have content with data into it, and also modules. Now we need to configure above modules as per our functionality on data.

Step 2. Configure the search server:

Go to configuration admin page (configuration/admin) in your Drupal 7 site and click on the search API in Search and metadata section. You should be now on Search configuration setting. We will create a search engine for our data. You should see page like below:

Configure the search server

Now click on Add server link. Give a name to your server I gave (MYSQL), Choose database service for your service class and click create a server. Your server should be like below.


Configure the search server


Step 3. Configure the search Index:

Now we will make our search index, which will index all data from using search server and database server. It will do indexing as the user search for data on site and give faster results. Go back to search API settings and click on Add Index link. You should be on below page now.Configure the search Index

Values for above form:

  • Index name: Business Information

  • Item type: Node

  • Server: MYSQL which you create earlier

  • Index items immediately: Checked

Click on create Index. Now we will select which field to be indexed from our data so we will select fields we want. In our case, we will select

  • content type

  • Address

  • Title

  • County

and click on save the configuration.

What is the outcome

we created our database server, Index server and added fields which need to be. As you added fields for indexing Facet API actually make Facet blocks of those fields.We will enable them later.

Now run Cron in your site which populate the Index.

Step 4. Create a view of your data which need to be Indexed and Displayed to your site user:

Install Views and enable it. Go to Structure > Views. click add a new view. Select below values for each field:

  • Show content: Business Information “This will be name of your Search server”

  • Create a page: checked

  • Path: node

  • Display format: Table

Your view information look like below:

Create a view of your data which need to be Indexed and Displayed to your site use

Click on continue & edit button. Now in the Fields section click on add fields and Filter Index node. Add Index fields you want to show to your user. Your selection will look like as below.

Create a view of your data which need to be Indexed and Displayed to your site use- 2

Complete all configuration of the specific field and click Apply Display. You are done with creating view. You are now able to see this view on your front page(/node).

Next step is to enable all blocks of your facet search. Earlier we added fields which needed to be Indexed. Actually when you add fields for indexing Facet API it creates Blocks of those fields respectively. You have to just enable them from Search settings.

Step 5. Enable Facet block from Search settings:

Go to configuration and click on Search API from search and metadata. Now just click on edit in You are able to see various configuration options like below.

Enable Facet block from Search setting

Click on Facets and enable facets you want. When you enable and save the configuration, it will create blocks of respective fields.

Step 6. Enable your Facet block from Blocks:

Now go to structures and blocks. Here you are able to see your block in Disable section just enable them in any regions of your theme.

Congratulations! Your site is ready. Visit your home page and it should look like as below. As you select options from blocks your main view shows you data as per your selection.


Facet API have many configuration options. You should take a look to them like showing selection in Blocks in Checkbox etc. However, facet API is not able to give you Multiple Facet search functionality. So, I am now working on developing custom module of widget and behavior which will give functionality of Multiple facet selection search. Facet API have OR and AND but only AND works not OR among fields.

Read my next blog on How to Drive through certain scenarios while implementing Facet Search API.

Please free feel to ask your queries related to Facet search in the comment section below. 

Topics: Drupal, API Management, Coding and Tutorial

How to upgrade Drush to work with Drupal 8

Posted by Nilanjana on Aug 14, 2015 10:28:00 AM

As Drupal developers, we all know about Drush. But for those who are unaware, Drush is a command line interface for Drupal. It provides almost all the commands for interacting with Themes/Modules/Profiles.

I have been using Drupal 7 for quite some time, but once I heard about Drupal 8, I wanted to see the new features it has come up with. Moreover, Drupal 8 has not released its stable version, so all of us can also contribute in the beta version.

To work on Drupal 8, I set it up on my local windows machine. But when I typed into my terminal window drush cc all, I got an error message:

Since Drush 6.x is only working with Drupal 6 and Drupal 7. So for Drupal 8, you have to upgrade Drush to 7.x.

Here are the two simple steps to Upgrade Drush 6 to Drush 7 :

  1. It’s great if you have already installed a composer, but in case you haven’t, follow thislink to install composer. This is for both Windows and Linux. You should also try to install it globally, so you can access it from anywhere. Below is the command and corresponding output for that command.
  2. Now you are ready to install Drush 7.x using Composer. Enter the following command in the terminal:

composer global require drush/drush:dev-master 

Hooray! Drush upgraded from 6 to 7. Upgrade command is same for linux and windows users.

Now Type:

drush cr 

drush en classy

Enjoy with development & contribute to Drupal 8.

Topics: Drupal, Architecture, Coding and Tutorial

Developer Tip: Unserialize Drupal7 Session Data

Posted by Nilanjana on Aug 12, 2015 10:42:00 AM

Use following function to get serialized session data in array form.

function modulename_unserializesession( $data ) {
  if(strlen( $data) == 0) {
    return array();

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value ) {
    $offset = $value[1];
    if(!is_null( $lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;

Topics: Drupal, Architecture, Coding and Tutorial

Six Sass tricks that work really well

Posted by Sanjay Rohila on Jan 21, 2015 5:41:00 PM

I have been using Sass in projects since last two years. There are lots of posts out there suggesting how we should use Sass, what are the best practices, and so on. Many of them say the same things which most of us have been practicing already. CSS/Sass is evolving very quickly, so best practices continue to change every week. It’s hard to stick to a single guideline or follow a few popular guidelines.


I read lots of articles, and follow new trends. I don’t agree with all of them, I just use things that can work for me and ignore the rest. Here is a list of points that I have been following or am about to.

1. Color Names:

There are lots of article arguing about color names. What should be the color name in Sass variable?
Example 1 (Name based on used position):
$menu-color: #ff0000;
.menu {
  color: $menu-color;

We can’t just copy this elsewhere.

Example 2 (Using generic names):

$red: #ff0000;
.menu {
  background: $red;
.footer {
  color: $red;

There are a few problems here. First, if we have to change the color for the footer, we can’t just change the $red variable. We have to introduce a new variable and use that. The second issue is that we have to change the color value from red to blue, we have to change the variable name too, otherwise it will be confusing ($red: blue).

Now, see this.

Example 3 (Override generic one by specific):

$red: #ff0000;
$menu-background: $red;
$footer-color: $red;
.menu {
  background: $menu-background;
.footer {
  color: $footer-color;

This solves the problem. We can change the color scheme by changing the variable name and color value at just one place (_variables.scss). We can also change the footer color in the same file without having to change it at the actual selector level.

When you have lots of color to work with, this would look very lengthy. So in future projects, I intend to use Sass-maps to store the colors in a single map variable (Array).

Example 4:

Edit Code on

$color: ();
@function color() {}
$footer-color: color(reddish); // (

This is not a fool-proof approach, but I can live with this for now. If you want a more complex structure then

$colors: ();
@function color($color, $palette: $colors) {}
$header-colors: (
 ‘header-menu’: color(raddish),
.menu—header {
 color: color(‘header-menu’, $header-colors);

Note: I choose color names from

2. Nesting:

Nesting is a cool and dangerous feature of Sass. Dangerous, because it can compile to a nasty, complex code if not used carefully.


nav {
  ul {
    li {
      a {
       color: red;

It will compile to nav ul li a {}, which is very specific and hard to override. It should be written as:

nav {
  ul {}
  li {}
  a {}

Note: The best way would be to use classes for ul, li and a without nesting. The above example has been given to explain the Nesting rule. Most times, I don’t go deeper than three levels of nesting, so I don’t have to use deep hierarchy selector or !important to override.

3. Extend:

It’s is a debatable topic in Sass: whether we should use @extend or not. I find @extend useful and used it for helper classes.


%text-bold, .text-bold {
 font-weight: bold;
%no-margin, .no-margin {
 padding: 0;

Harry Roberts wrote about the @extend/@mixin debate. According to hm, when we use helper classes, the selectors also pick the same properties, but they are not connected.


%no-margin { margin: 0; }
.nav--main { @extend %no-margin; }
.footer__copyright { @extend %no-margin; }
The two are not connected in any way. But they will compile to:
.nav--main, .footer__copyright { margin: 0; }

I am going to keep using both, and use @extend only when it makes more sense as below.


%dark-heading { font-weight: bold; }
h1 { @extend %dark-heading; }
h2 { @extend %dark-heading; }

4. Context Selector (`&`):

This one is always useful.


a {
 color: $link-color;
 &:hover, &:focus {
 color: darken($link-color, 30%);
 &.has-children {
 color: lighten($link-color, 40%);

5. Error Handling:

If we provide the wrong value in mixin, variable, and function then the compiler throws up a weird error with line number (and page without css). Sass-3.4 has @error directive which can throw a custom error message in the console itself. So we can provide a useful message instead of the default one.


@function color($color) {
 @if not map-has-key($colors, $color) {
 @error “#{$color} not found in $colors.”;
 @return map-get($colors, $color);

6. Compass file-system Access:

I have never used this one. We can get image properties in CSS using the compass function. Compass can access the local file system.


$img: “path/to/img”;
.fixed-width-img {
 width: image-width($img);

Other than these, I use Compass for mixins, and some custom or available (read contributed) mixins.


I don’t claim these to be the best practices, but it gets my work done in live projects. It fulfils our requirements and helps in writing DRY and maintainable code. Things will change over time. Stay tuned.

Further reading:

Topics: Coding and Tutorial, Framework and Libraries

How to find the culprit? Debug Drupal like a pro!

Posted by Nilanjana on Oct 7, 2010 3:57:00 PM

Many times we are in a situation where "something is not working as expected". Some of these situations are straight forward and thus are easily rectified, but sometimes the culprit is not as obvious. How to go about these situations?

I would like to share with all of you some thoughts that I gained from my day to day work. Normally one would think that debugging always require very deep knowledge of the underlying system, but it is actually the observational and reasoning abilities that gets you to the goal.

I would discuss the general steps to find a problem's cause in a Drupal system one by one. My apologies in advance as I am going to be bit technical here.

Quest to find *The Culprit*:

Basic knowledge of the system:

You should at-least have basic knowledge of the system and its integration points (if any).

Collect the symptoms:

Collect as many of them. Symptoms of a problems are normally the clues which will lead your investigation. Make your system spit out as much errors/warnings as it can. Log them somewhere. 

Understand the symptoms:

These are clues to success. Observe them closely , as they will tell you about the probable root cause. Like movies, clues are either to guide or misguide you. so take both situations into account. Search around to understand the symptoms. Take Google/your team's help in this regard.

Follow the trace:

 Don't hesitate taking help from existing tools/tricks to relate clues and create the route to cause. If available, do use back-tracing facilities. It would help you find the order in which events occurred. e.g PHP has debug_print_backtrace() which does this. In Drupal you may use Devel module. Every system has sophisticated tools for debugging problems (Xdebug etc), use them as and when needed.

Divide and Conquer:

Sometimes there are more than one culprits, use this tried and tested approach to isolate and find them.

Enjoy after you find 'em:

You found it! Now it is time to celebrate. Speak out your favorite punchline or dance on your chair. It will boost your morale bigtime. Make it memorable so that you and other can use your case to solve similar ones.

Don't be disheartened if you can't find it:

Yeah, this might also happen. But don't worry, this just means you need some more time or resources. 

Plan for a fix:

Well, try to get it fixed for once and all. Never ignore any problem. Most of the big problems start with being very simple. If you don't have time to fix it, document it properly for future references.

Thats all. I hope it would be of some help to the developers. 

Topics: Drupal, Architecture, Coding and Tutorial


Write to us

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms Of Service apply. By submitting this form, you agree to our Privacy Policy.

See how our uniquely collaborative work style, can help you redesign your business.

Contact us