M/s VIKASH TECH - We Write Imaginations to Codes..!!

How to write generic codes ?

generic coding

I have been working with students, interns and lot of great developers of future. It has always been a concern at beginning and intermediate stages to write generic codes for functionalities that are used multiple times in a project, or even sometimes when the same functionalities has to be built in different projects.

This building of generic codes have led to multiple good and bad options. It cannot be said that there are fixed parameters to build generic codes. Still, for the sake of understanding the way of digging out generic codes, I have jotted down some basic points below. If you are a serious developer, you will take away the good for you stuff.

Way-point 1

First of all, you need to start thinking from the small point but you need to keep a satellite vision on everything.

What I suggest to coders, is to develop the basic functionalities first. Separately, and with clean codes. Written with good comments of everywhere.

Let’s begin with a simple statement to showcase data from database.

This is not the best way of doing it. It’s for understanding purpose only

<?php
 //For connection with database 
 $connection = mysqli_connect('localhost','database_user','database_password', 'database_name');

 // Creating query for fetching data from "user_details" table
 $query = "SELECT * FROM `user_details`";

 //Executing query and storing data in $result variable.
 $result = mysqli_query($connection, $query);

 //checking if we get some result
 if($result){
    //If some result comes, we will iterate it and send the same as output
    while($row = mysqli_fetch_array($result)){
      //showing output as object
      print_r($row);
    }
 }
 
?>

Way-point 2

Once you are done coding the basic part. You can move forward with doing the changes. The changes that we are going to discuss below might first seem to be a bit confusing and multiple questions may arise in your mind. Digest them for a while, and as we go forward, all of them will be clarified.

As the basic part is developed, we need to change the basic part into functions (reusable codes), so that we can call them from anywhere just by hitting it’s name.

<?php
 //For connection with database 
 $connection = mysqli_connect('localhost','database_user','database_password', 'database_name');

//Function to fetch data
function fetchData(){
 // Creating query for fetching data from "user_details" table
 $query = "SELECT * FROM `user_details`";

 //Executing query and storing data in $result variable.
 $result = mysqli_query($connection, $query);

 //checking if we get some result
 if($result){
    //If some result comes, we will iterate it and send the same as output
    while($row = mysqli_fetch_array($result)){
      //showing output as object
      print_r($row);
    }
 }
}
//Calling the above function to show data.
fetchData();
 
?>

The above code is just to suggest “Convert basic part as a reusable code”.
Now, once you are done with it, we can move forward with making further changes and using the function for different purposes.

Way-point 3

Using same function for multiple queries can be done by parameter passing. To do this, you need to find out the parts inside the function that can be changed to provide different outputs.

In our case, we can change the query to fetch data from different table.
We can also change the query to fetch filtered data from database, using WHERE clause.
We can setup different way of outputs from the same function.

Let’s see how we can do this.

<?php
 //For connection with database 
 $connection = mysqli_connect('localhost','database_user','database_password', 'database_name');

//Function to fetch data
function fetchData($tablename, $clause ="", $output){
 // Creating query for fetching data from "user_details" table
 $query = "SELECT * FROM `".$tablename."` ".$clause;

 //Executing query and storing data in $result variable.
 $result = mysqli_query($connection, $query);

 //checking if we get some result
 if($result){
    //If some result comes, we will iterate it and send the same as output
    while($row = mysqli_fetch_array($result)){
      if($output == 'option'){
        echo "<option value='".$row['name']."'>".$row['name']."</option>";
      }

      if($output == 'object'){
        //showing output as object
        print_r($row);
      }
    }
 }
}
//Calling the above function to show data.
fetchData('user_details', 'WHERE `sno`=1', 'option');
 
?>

In the above code, you can see how the function above has been changed to be used for fetching data from any table setting up clauses and output standers too.

Way-point 4

Once you are done converting the functions to dynamic and reusable ones, you can now move forward spiting the code in different pages and using only the ones needed at a fixed time span.

Splitting code into different pages will not only help in making it more readable but also will keep it optimized and enhance the performance of the server.

Before we end, I’ll suggest you to keep security of your codes too. Make sure that you use proper filtering of data and safeguard yourself from attacks.

A simple way of filtering data before sending it to your MySQL is by using mysqli_real_escape_string(), You can use it in reusable one too.

<?php
 //For connection with database 
 $connection = mysqli_connect('localhost','database_user','database_password', 'database_name');

//function for filtering and checking if not empty
function _f($inp){
 if(!empty($inp)){
  return mysqli_real_escape_string($connection, $inp);
 }else{
  return false;
 }
}

//Function to fetch data
function fetchData($tablename, $clause ="", $output){
 // Creating query for fetching data from "user_details" table
 $query = "SELECT * FROM `".$tablename."` ".$clause;

 //Executing query and storing data in $result variable.
 $result = mysqli_query($connection, $query);

 //checking if we get some result
 if($result){
    //If some result comes, we will iterate it and send the same as output
    while($row = mysqli_fetch_array($result)){
      if($output == 'option'){
        echo "<option value='".$row['name']."'>".$row['name']."</option>";
      }

      if($output == 'object'){
        //showing output as object
        print_r($row);
      }
    }
 }
}
//Calling the above function to show data.
fetchData('user_details', 'WHERE `sno`=1', 'option');
 
?>

As you can see in the above code, I have created a function to check if the input is not empty and return the escaped string or false. It will secure my code a bit.

Why have I use a name like _f() its because, every-time I use it, I don’t want to increase the code size, rather it will only take 2 characters to call the function.

CONCLUSION

You can create reusable codes, just by starting from the basic units, and moving forward by making small small changes and taking it to a complex and more reusable code.

Always have a satellite view of your final product and start coding it from the basic part.
Your code will start changing from a fixed code to a generic code, and will be available for using it multiple times in the same project or can be used in different projects too.

Category :

Comments

No comments found.

Leave a Comment

Latest Posts

PHP Security

Website Security - PHP: Implementing Security To Your Website

Security is one of the major concerns today and when it comes to coding, It becomes a point to re-think…

Total blocking time

Total Blocking Time (TBT): How it affects your website?

It's great to create a website and move your business online. Almost everyone does the same but there are certain…

Common variations of the websites

Common variations of the website, choose which suits you the best.

There are lots of options for creating websites, here we are going to share you some common types of websites…

E-Commerce - Want to sell online?

E-Commerce : Want to sell online?

It is always a good idea to move your business with the latest trend. Today, when the entire world is…

Tags