How NOT to structure your PHP code

February 5, 2016    PHP MVC

Mixing application code and presentation code

It can be common in PHP to see all the code for displaying some data from a database in a single script file, like this:

<?php

$db = new PDO("...", "username", "secret");
$posts = $db->query("SELECT * FROM posts")->fetchAll();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $stmt = $db->prepare('INSERT INTO posts VALUES (...
}

?>
<html>
<body>
    <form method="post">
        ...
    </form>
    <?php foreach ($posts as $post): ?>
        <h2><?php echo $post["title"]; ?></h2>
    <?php endforeach; ?>
</body>
</html>

Basically, the code that does stuff is mixed up with the code that shows stuff. This is fine if it’s a one-off script, but as part of a bigger website or application, it can very quickly get complicated and difficult to maintain.

File organisation

The default way to access script files in a browser is directly, by name. So the name of the script becomes part of the URL. If a script is in a subdirectory, then that becomes part of the URL too. Basically, the URL = the file location, like this:

URL = file location

The problem with this is that you can end up either repeating yourself, or having includes with files all over the place and basically a big pile of spaghetti, like this:

PHP files all over the place with includes everywhere

A site like this can be:

  • Difficult to maintain: files including files in different directories all over the place;
  • Difficult to develop: application logic is mixed up with presentation; a programmer and a designer can’t work on the same file;
  • Insecure: database passwords are in a file in a publicly-accessible folder.

A solution

These problems can be overcome by using a framework. A framework is a library of code. It provides structure that you can use to build your application on. Advantages include:

  • You can code faster and reuse code.
  • Easier for more than one person to work on the code at once.
  • The code is less complicated, so therefore easier to maintain.
  • It’s more secure: database passwords etc. can be stored outside of the publicly accessible folder.

One of the most common and easiest to understand types of framework is model-view-controller, or MVC.

Learn more by writing your own PHP MVC framework from scratch, my latest online Udemy course.



comments powered by Disqus