Why You Should Use a Micro-Framework For Your PHP Projects.

Kelvin
Kelvin
Aug 24, 2017 · 7 min read

For most developers who start working with PHP, plain PHP files with embedded HTML is how we learn to create web apps/websites. This is the format that most beginners(including myself) learn to create web apps using PHP. However, as you get more experienced and start to build more complex applications with real purpose/function, this method of development quickly becomes less feasible over time. This is where micro-frameworks come in. For this tutorial, I am going to assume you already have a local server such as xampp already running on your computer.

Before I continue, I should state that micro-frameworks are mostly suitable for small to medium sized projects and/or projects that require little overhead or boilerplate in the set up. If you’re working on a large project such as a social network or an e-commerce site, consider a full-fledged framework. An alternative would be to combine different micro-frameworks that have different functions in your application. Be careful with the later option as some micro-frameworks my not play nice with each other and for that reason, I would only recommend that option to advanced developers who know exactly what they are doing. That being said, let’s dive into the topic at hand!

The Good Old Fashioned Way

Creating web apps the old fashioned way refers to the practice of embedding HTML inside your php files. We’re going to start with a simple setup. In your htdocs folder inside xampp, create a directory for your project and call it “plain”. Inside this project folder, create a folder named “index.php”.

Now let’s type the following code into index.php

<?php
echo "We're up and running!";
?>

All you have to do now is visit “http://localhost/plain” on your browser to the message above displayed on the screen. At this point, we’re ready to explore this further.

Now we’re going to embed some HTML on this page. Update the code in your index.php file to this:

<?phpecho "Hello, world!";
// You can change the variables below to whatever you like.
$name = "Kelvin Mwinuka";
$age = 20;
?>
<html>
<head>
<title>Plain HTML</title>
</head>
<body>
<p>My name is <?php echo $name; ?> and I am <?php echo $age?> years old.</p>
</body>
</html>

If you load the web page again, you will notice that the HTML is rendered with the php variables parsed and their values included. If you’re wondering why having HTML inside a PHP file doesn’t give you an error, it’s simple. The server only parses everything inside the <?php ?> tag and passes everything else on to the client as it is.

If you study the code above, you’ll notice that we have to declare multiple <?php?> tags within the HTML whenever we want to run any PHP code in that section. This seems okay so far as we have only needed to 3 of such tags. This can become exponentially tedious the more complicated the application gets. Now lets have another example where the index file has a form that it handles. Let’s update the code in the index file to the following:

<?php
// This condition checks if all the POST variables have been set.
if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['conf_password'])){
echo "Everything is set!";
} else {
echo "Something's not right :(";
}
?>
<html>
<head>
<title>Plain HTML</title>
</head>
<body>
<form method="POST" action="index.php">
<input name="username" type="text" placeholder="Username" required/></br>
<input name="password" type="password" placeholder="Password" required/></br>
<input name="conf_password" type="password" placeholder="Confirm password" required/></br>
<input type="submit" value="Submit"/></br>
</form>
</body>
</html>

As you can see, the code above is becoming increasingly untidy and this is only a simple form!

Advantages of The Good Old Method

An argument can be made that there is a suitable application for this approach. One could be made for landing pages. If you’re creating a single landing page with only a few outgoing links and not much interaction or data processing, then this method is sufficient. Why go through the trouble of setting up an entire micro-framework and configure it just for a single page?

Another advantage is that is simplifies the learning process. As stated before, this is the approach used in most introduction courses to PHP web development, it eliminates the overhead of setting up an environment just to learn basic PHP.

Disadvantages of The Good Old Method

Although we’ve stated a couple of benefits for this method, in production, it simply isn’t feasible especially for a project that is expected to grow in size and complexity over time.

On large projects, there will usually be front-end and back-end developers. By mixing the front-end and back-end code together, you create the need for both of these developers to dive into the same code to make changes. This will expose back-end code to front-end developers who do not need to be interacting with it. Alternatively, if the page is visually complex, it will force back-end developers to go through a lot of mark-up code in order to find the PHP code that they need to be editing. This structure can be made even worse if the JavaScript and CSS are also included in the same file using the <script> and <style> tags respectively. This is simply poor design.

Enter Micro-frameworks

For a simple project that requires some level of separation between the back-end code and the front-end code, a micro-framework is ideal. For the following example, I will be using the slim micro-framework and the twig template engine. I will assume that you have the slim and the composer package manager installed and dive right into the code.

We will create an index.php file which will serve the purpose of routing all requests to the appropriate url. The code that handles a particular url request is a controller. We will set up 2 controllers for the home page and the sign in page of a website respectively.

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
... $app = new \Slim\App([
'settings' => [
'displayErrorDetails' => true
]
]);
//.. Configuration Code .. $app->get('/', function(Request $request, Response $response){ // Controller for the home page.
})->setName('Home')
$app->map(['GET', 'POST'], '/signin', function(Request $request, Response $response){ // Controller for the sign in page.
if($request->isPost()){
// Handle post request
} else {
// Handle get request
}
})->setName('signin')
?>

The above example is by no means as detailed as a typical index.php file in a slim project. This is because it is made to just serve as an example of how controllers work in slim. You can see that each web page has its own method that specifies the url, request method and then specifies the request and response objects that can be accessed and manipulated in your logic. Now, if you’re wondering how you can link the controller to it’s HTML code, here’s the code you can include at the end of a controller that will do just that:

return $this->view->render($response, 'about.html', [
// Template arguments
]);

The above code specifies the HTML template that is relevant to this controller and passes variables to the HTML template in the form of an associative array. The HTML template folder will typically have a base layout that can be extended by all other HTML files. This is the basic layout that will be shared across the entire site.

Here is an example of the base HTML layout file:

<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>

All the files that need to be included for the entire project such as scripts and style sheets should be included in this file.

Here is an example of an individual page’s HTML file that extends the above base layout and then overrides the title and content blocks of the base layout:

{% extends "base.html" %}{% block title %} Sign In{% endblock %}{% block content %}  <form method="POST" action="{{ path_for('signin') }}">
...
</form>
{% endblock %}

Advantages of Micro-frameworks

There is an abundance of advantages that come with micro-frameworks. Firstly, as is evident in the example above, the back-end and front-end code is separated. This improves the developers’ work flow as they only have to look at code that is relevant to them. The back-end developer simply has to pass the variables to the template and the front-end developer will decide how to display it.

Another advantage offered is the ability to “extend” HTML layouts. If there are elements that need to be static across the entire website, it is more productive to be able to put them in one file for the convenience of not having to edit multiple pages in the future in order to make one change.

The micro-framework makes it more feasible to increase the size of the project. Adding more controllers and templates is a fairly straight-forward task for most micro-frameworks.

Relative paths are also extremely easy to use in projects that use micro-frameworks. In the template example above you can see that the form action is set to “{{ path_for(‘signin’) }}”. This simply tells the template engine to find a controller named ‘signin’ and assign that as an action. This means that you do not have to make massive adjustments if you’re deploying to a different location or your project structure changes slightly.

Disadvantages of Micro-frameworks

As big a fan as I am of micro-frameworks, they still do come with their drawbacks.

Firstly is they can be difficult to grasp for beginners looking to learn web development as they have a steeper learning curve than plain PHP. Another problem is that different micro-frameworks take different approaches to the development process and having to learn a new framework for different projects can delay development of a project.

Conclusion

We have looked at both approaches of web development and weighed some of their advantages and disadvantages. With all that considered, I heavily lean in favor of micro-frameworks as the preferred method of web development simply for the functionality and convenience that they offer to the developer. Plain PHP with embedded HTML is the best way for beginners to learn development but this should only be a temporary stage as it’s key to graduate to micro-frameworks and eventually, full web frameworks in order to be productive and build scalable applications with good structure.

In my next post, I will solve some mysteries in this post by giving a short tutorial on setting up xampp, php, composer, and slim. I will also go into configuring your first slim project.

If you’re interested in more content from me, visit my personal blog. If you are interested in acquiring my services, visit my personal website and feel free to contact me.

Kelvin Mwinuka

Sharing knowledge on web and mobile app development.

)

Kelvin

Written by

Kelvin

Full-stack software developer. #WebDev #Programming

Kelvin Mwinuka

Sharing knowledge on web and mobile app development.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade