PHP Tutorial

Step 2

PHP Tutorial

In this tutorial we will create a simple twitter copycat. In step 2 we will focus on organizing our code better.

Step 2

1. There are certain parts of our code that will be executed in all pages. Namely the connection to the database.

Lets add a new file called init.php and move the database connection code to that file:

<?php
  $conn = new PDO('pgsql:host=HOSTNAME;dbname=USERNAME', 'USERNAME', 'PASSWORD');
  $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>

2. Instead of doing the database initialization in our list_all.php page we will simply include this file:

<?php
  include_once ('init.php');

  ...
?>

3. The code that access the database should also be kept in a separate file. This will allow us to reuse the code if needed. Lets create a new file called tweets.php that is responsible for all queries related to tweets.

<?php
  function getAllTweets() {
    global $conn;
    $stmt = $conn->prepare('SELECT * FROM tweets JOIN users USING (username) ORDER BY time DESC');
    $stmt->execute();
    return $stmt->fetchAll();
  }
?>

4. We can now use this function to get all tweets from the database. Replace the corresponding code from the list_all.php page with just:

include_once ('tweets.php');

$tweets = getAllTweets();

5. We should now have the following files: list_all.php, style.css, init.php and tweets.php.

Lets try to organize these files better by putting them in specific folders:

css/style.css
pages/tweets/list_all.php
database/tweets.php
config/init.php

6. To get our page working again we have to correct the include paths in several places. To make this easier lets start by adding two constants in our init.php file:

<?php
  $BASE_DIR = '...';
  $BASE_URL = '...';

  ...
?>

Replace the empty strings with the full path to your project and the full URL to your page root. We can now make the necessary changes.

In the list_all.php file we have to change the include commands to:

<?php
  include_once ('../../config/init.php');
  include_once ($BASE_DIR . 'database/tweets.php');
  ...
?>

We also have to change the way in which we declare our CSS file:

  <head>
    <title>Example Twitter</title>
    <link rel="stylesheet" href="<?=$BASE_URL?>css/style.css">
    <meta charset="utf-8">
  </head>

7. One last thing before we finish this step. Currently we access our initial page by going directly into our pages/tweets/list_all.php page. That’s not very elegant. Lets solve this by adding a new file named index.php to our base directory that redirects to this page:

<?php
  header('Location: pages/tweets/list_all.php');
?>

You can find the complete code after step 2 here. In step3 we will separate the presentation and business layers by using Smarty.