I made a package to manage database connection, it was awesome experience! 
Tags: php, programming, database, sideprojects
Published: 2021-08-06 17:00:24

I was working on [side project to explore APIs in native PHP](https://dev.to/theahmedlatif/my-first-api-using-native-php-4jjf), 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](https://github.com/theahmedlatif/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_).
```bash
#Database#
HOST = "localhost"
DATABASE_DSN = "mysql"
DATABASE_NAME = "sample_db"
DATABASE_USERNAME = "sample_username"
DATABASE_PASSWORD = "sample_password"
```

* 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.
```php
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()";
        }
    }
```

* 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
<?php
require_once dirname(__FILE__).'/vendor/autoload.php';
use Envelope\Database\MysqlDatabase;

$database = new MysqlDatabase();
$database->getConnection();
```

#### 2- CRUD statements using binders:
Simply write native mysql statement passing any arguments using binders array.
Take this example of creating a new user.

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

$database->insert("INSERT INTO users (userName, userPassword, userEmail)
                                    VALUES (:userName, :userPassword, :userEmail)",$binders);
```

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

```php
$database->closeConnection();
```

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](https://packagist.org/packages/talmira/) to use it through composer.
```Bash 
composer require talmira/envelophp
```

You can review full explanation for my first and only package so far :) :) [here](https://github.com/theahmedlatif/envelophp#readme).

###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](https://github.com/theahmedlatif/Sho-rt) and I used this package, I'll write an article soon to explain it more!