DEV Community

Ahmed AbdElLatif
Ahmed AbdElLatif

Posted on

1

I made a package to manage database connection, it was awesome experience!

I was working on side project to explore APIs in native PHP, when I realized that I can make reusable piece of code to manage database connection in process of practicing my php OOP skills.

So I started to think about writing a package that handle database connection and queries for native php projects, so I created Envelophp, hereunder how I approached this side-project.

  • I tried while creating Envelophp to apply DRY concept, so basically the idea is to have database credentials added in .env file (which is added to .gitignore to avoid credentials leakage).
#Database#
HOST = "localhost"
DATABASE_DSN = "mysql"
DATABASE_NAME = "sample_db"
DATABASE_USERNAME = "sample_username"
DATABASE_PASSWORD = "sample_password"
Enter fullscreen mode Exit fullscreen mode
  • Then I made within Environment Variables Class a method to parse .env file and store credentials provided in it. NB: I plan to extend to more variables other than database credentials.
public function getDatabaseVariables()
    {
        try {
            //open .env file in read mode
            $file = fopen(dirname(__DIR__, 4) . '/.env', "r");

            while (($line = fgets($file)) !== false) {
                $validate_line_from_env_file = preg_match('~^[a-zA-Z]~', $line);
                if ($validate_line_from_env_file) {
                    $env_file_text = explode('= "', $line);
                    $env_variable_key_length = strpos($env_file_text[0], " ");
                    $env_variable_key = substr($env_file_text[0], 0, $env_variable_key_length);
                    $env_variable_value_length = strpos($env_file_text[1], "\"");
                    $env_variable_value = substr($env_file_text[1], 0, $env_variable_value_length);
                    if ($env_variable_value == true) {
                        $this->variables += [$env_variable_key => $env_variable_value];
                    } elseif ($env_variable_value === "") {
                        $this->variables += [$env_variable_key => ""];
                    }

                }
            }
            fclose($file);
            return $this->variables;
        } catch (Error $error) {
            return "Error: $error->getMessage()";
        }
    }
Enter fullscreen mode Exit fullscreen mode
  • After that I inherited Environment Variables Class in a MysqlDatabase Class to make use of the variables to make all required functions related to mysql database as following:

1- Create Connection

  • Simply require autoload.php in your file where you want to connect to your database.
  • Then use the MysqlDatabase namespace
  • Now you are ready to create a new instance of MysqlDatabase.
  • to make a database connection call getConnection().
<?php
require_once dirname(__FILE__).'/vendor/autoload.php';
use Envelope\Database\MysqlDatabase;

$database = new MysqlDatabase();
$database->getConnection();
Enter fullscreen mode Exit fullscreen mode

2- CRUD statements using binders:

Simply write native mysql statement passing any arguments using binders array.
Take this example of creating a new user.

$binders = [":userName" => $userName, ":userPassword" => $userPassword, ":userEmail" => $userEmail];

$database->insert("INSERT INTO users (userName, userPassword, userEmail)
                                    VALUES (:userName, :userPassword, :userEmail)",$binders);
Enter fullscreen mode Exit fullscreen mode

3- Close database connection by calling closeConnection() method:

$database->closeConnection();
Enter fullscreen mode Exit fullscreen mode

By writing those few lines you make a database connection, apply the required query, then close the database connection.

Also I learnt how to publish this script on Packagist to use it through composer.

composer require talmira/envelophp
Enter fullscreen mode Exit fullscreen mode

You can review full explanation for my first and only package so far :) :) here.

Finally...

it was a very educative experience to work on this application, I'd appreciate any feedback to improve my skills.
I revamped an old project of mine to shorten URLs and I used this package, I'll write an article soon to explain it more!

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay