Johan Broddfelt
/* Comments on code */

How to use classes

Now it is time to uncomment our File::getFileVersion() for main.css and main.js. So let's start by adding a folder called classes and create the file File.php with a capital F.

<?php
class File {
    // Get the last change date of the file as a version number
    function getFileVersion($filename) {
        return date('YmdHis', filemtime($filename));
    }
}

Now we have a class called File and it contains a function called getFileVersion. But we can not access it yet. We need to include it into our main_template.php. We could do that my adding the line require_once('classes/File.php');. And that is often used in other languages and give you a quick overview of what classes are used. But I want to write as few lines of code as possible and php offers a function called __autoload() that automatically includes the class file we needed. We will add that function into our global.php as follows.

<?php
function __autoload($className) {
    // This will include the class files as they are needed.
    // The className need to be the same as the name of the included class
    require_once('classes/' . $className . '.php');
}

Now we can uncomment the two lines in our main_template.php

<link rel="stylesheet" type="text/css" href="main.css?v=<?php echo File::getFileVersion('main.css'); ?>">

and

<script type="text/javascript" src="main.js?v=<?php echo File::getFileVersion('main.js'); ?>">

Try to run the page now and take a look at your source. There will now be a visioning number after these files like this:

<link rel="stylesheet" type="text/css" href="main.css?v=20150911223044">

The reason why we want this is because these files are usually (hopefully) cached in the browser. And as long as you do not change them it is ok. But as soon as you make a change, you do want your visitors to get the latest version. This will tell the browser that the file has changed and make it download the new one.

- framework, php, classes, software

Follow using RSS

<< Adding content Connect to a database >>

Comment

Name
Mail (Not public)
Send mail uppdates on new comments
0 comment