Simple MVC Framework with PHP — .env

Chibuzo Miracle
2 min readOct 13, 2022

--

Setting and loading .env variables into our PHP application automatically.

NB: First, I would like to warn you that I used a code-as-you-think approach in writing this 😊. It would be to your interest if you use this article for educational purposes only and not in production. Thanks.

I think I'm getting a hang on this whole warning note before starting 😂, it gives off that nuclear reactor vibe 😂.

Alright, This might be the shortest tutorial in this series. We are going to basically refactor the way we set configuration variables to using the .env approach as it is globally or should I say generally acceptable approach and from here onwards, we will be depending on some packages that work with .env file. The library we would be using for this purpose is the phpdotenv library by Lucas and Campbell.

This tutorial is one of many in a series, Simple MVC Framework with PHP. To be well-informed and not run into any complications, make sure you follow the tutorial as prescribed.

1: Simple MVC Framework With PHP

2: Simple MVC Framework With PHP (bootstrapping)

3: Simple MVC Framework With PHP (Routing)

4: Simple MVC Framework With PHP (View)

5: Simple MVC Framework With PHP (Request Parsing)

6: Simple MVC Framework with PHP — Middlewares(A Chain of Responsibility Design Approach).

First, We would import the package using composer.

composer require vlucas/phpdotenv

after which we would create a .env file in our application root, this file will look something like this:

The next step would be to alter our config/app.php file and the public/index.php file, respectively:

Looking at the new index.php file, you can deduce that the application flow has been altered a little. Now we define an APP_ROOT, require our autoload file, load all libraries that the Framewrk.php needs to function like our .env library in the app.php then require the web.php file.

Don’t forget to follow as more tutorials are loading.

--

--

Chibuzo Miracle

B Eng A&B Engineering || Software Developer || Technical Writer