Ad Rotator
For this tutorial we'll assume that you wanted to display some sort of ads on your website. More specifically, let's assume you sold adspace on your site for one week. So every week you would display a new ad on your page. Customers would purchase one of the 52 weeks in the year. Therefore, you'd assigned them one of the weeks in the year in which their ad would display continuously.
REQUIREMENTS
- The URL of the image to be displayed
- The alternate text for the <img> tag in case the picture should not display
- The number of the week the customer purchased
LIMITATIONS
This is a very oversimplified example. For instance, you could choose to rotate the ads randomly. You could give the customer access to the database (via some unique username and password) in order to change the image (just in case they change their minds or they'd like to have a different image each day of the week). Deletion of the ads is not taken into account, therefore once the ad is included into the database it will stay there. No sort of CSS formatting or HTML tags will be given, only the raw code necessary to illustrate the mechanics of how Mimesis works. No error handling, I'm assuming all data will be entered properly into the form for passing into the database (this includes thing such as entering the same week twice, omitting certain fields in the form, improper values, etc.). FILE PERMISSIONS ARE NOT GIVEN, on some servers this can cause your script to malfunction so you need to make changes to this code (in terms of the file permissions to use) in order to get it to work on your server.
STRUCTURE
There will be two files. One which the owner of the site would use to add the ads into the database, and finally the page that would actually display the ads.
CODE
First and foremost to use Mimesis you will need to have all the mimesis files in one location on your server. We'll assume they're located in a folder called mimesis. In order to use Mimesis you'll need to include the following directive into your code:
require_once('mimesis/Mimesis.php');
Secondly, we need to think about the form we'll be using to accept the input:
<form action="entry.php" method="post">
URL: <input type="text" name="url"><br>
ALT: <input type="text" name="alt"><br>
WEEK: <input type="text" name="week"><br>
<input type="submit">
</form>
Now we can go ahead and code the form to appear if the user has not yet submitted it as follows:
<?php
require_once('mimesis/Mimesis.php');
if(!isset($_POST['url']) || !isset($_POST['alt']) || !isset($_POST['week'])){
?>
<form action="entry.php" method="post">
URL: <input type="text" name="url"><br>
ALT: <input type="text" name="alt"><br>
WEEK: <input type="text" name="week"><br>
<input type="submit">
</form>
<?php
}
?>
All that's left is to consider how to create the database once the user submits the form. First, as the coder for the database you need to be aware of how Mimesis creates the database. Databases use tables with rows. Mimesis has a 1:1 relationship with these constructs as follows:
- Table = File
- Row = Array Key
- Column Headings = Array Keys
- Fields = Array Values
In this Ad Rotator example we wish to create a Table that stores the different ads in each of its Rows with Column Headings of url, alt, and week. Let's look at this graphically (with some hypothetical ad entries):
| url | alt | week | |
|---|---|---|---|
| 000 | http://www.someurl.com/someimage01.jpg | Ad for week 1 | 1 |
| 001 | http://www.someurl.com/someimage02.jpg | Ad for week 3 | 3 |
| 002 | http://www.someurl.com/someimage03.jpg | Ad for week 2 | 2 |
| ... | ... | ... | ... |
In order to get this information into PHP code we need to first construct an associative array (i.e. an array with non-numerical keys). The code is as follows:
$adData =
array(
'row label' => array(
'url' => 'urlLocation',
'alt' => 'alternateText',
'week' => #
)
);
Where each italicized part corresponds to the data submitted through the form (with the exception of the row label which is automatically generated by the code). Which we would code as such:
$adData =
array(
'000' => array(
'url' => $_POST['url'],
'alt' => $_POST['alt'],
'week' => intval($_POST['week'])
)
);
This array we've constructed is analogous to one row in the table. Now we just need to create a way to store it into a Table so that we'll have our database operational. For that we need to use the Mimesis class. For the purposes, of this example we'll assume that you wish to call your table 'adTable'. Couple of things to remember when constructing a Mimesis object:
- The first parameter denotes the location on your server where you wish to store the table
- The second parameter denotes the name of the table
- The third parameter denotes the name of the structural file for the table
For our example, these 3 parameters will be the following:
- The current working directory of your script
- 'adTable'
- 'ts_adTable'
Let's look at the PHP code for clarification:
$cwd = realpath(dirname(__FILE__));
$tableName = 'adTable';
$mimesis = new Mimesis($cwd, $tableName, 'ts_' . $tableName);
This may seem a bit daunting at first, but if you're familiar with any sort of spreadsheet package we're sort of doing the same thing. The rows are all numbered in a spreadsheet package. In Mimesis you have to create numbers for your rows. In this case we're going to create the first row which we call 000. In the spreadsheet the columns are lettered. In Mimesis we named them in the associative array, we also need a place to store them (the reason we need another file to store the column headings in is because we don't want to repeat the same data over and over, therefore we store them in a separate file once).
However, returning to our example we also need to ensure that the Table doesn't already exist. This is because we need to consider the situation where you've already added the first ad and you're now adding subsequent ads. Therefore we perform a check to see if the table exists, we use the Mimesis::tableExists() method to see if the table already exists and branch accordingly with an if statement. Also, we need to keep in mind that since things can happen simultaneously on a network you can't rely on your if statement because we don't know if someone else performed the same if statement check just a nanosecond ahead of you and so wrote in an ad, and then you wrote yours and overwrote theirs (this is what is referred to by atomicity of data in a database). Fortunately, the Mimesis package allows us to lock things in a sort of suspended time state so that we can make empirical updates to it (the default behavior is to check for the lock to ensure atomicity).
if($mimesis->lock()){ // This will fail if another process already has a lock on the object
if(!$mimesis->tableExists()){
// If the table doesn't exist we'll need to create it and add the first row
}else{
// If the table does exist we need to check how many rows there are so we know what to name the next one
}
}else{
trigger_error('Could not acquire lock on table', E_USER_ERROR); // Crash the program if a lock isn't acquired
}
Let's look at the branch where the table does not yet exist. It's very straightforward.
$mimesis->insertRow($adData); // Creates the row '000' in the newly created 'adTable'
Now let's look at the branch where the table does already exist. A tad more complicated since we need to determine a different designation for the new row in the table.
$rowName = reset($mimesis->entries()); // This step returns the number of rows present in the table
$rowName = str_pad($rowName, 3, '0', STR_PAD_LEFT); // Since they're numbered from 0 we use the count to number the last one
$adData = array($rowName => reset($adData)); // Redefine the data array
$mimesis->insertRow($adData); // Creates the new row in 'adTable'
So let's take a look at the finalized code (for the database entry form at least).
entry.php
<?php
require_once('mimesis/Mimesis.php');
if(!isset($_POST['url']) || !isset($_POST['alt']) || !isset($_POST['week'])){
?>
<form action="entry.php" method="post">
URL: <input type="text" name="url"><br>
ALT: <input type="text" name="alt"><br>
WEEK: <input type="text" name="week"><br>
<input type="submit">
</form>
<?php
}else{
$adData =
array(
'000' =>
array(
'url' => $_POST['url'],
'alt' => $_POST['alt'],
'week' => intval($_POST['week'])
}
);
$cwd = realpath(dirname(__FILE__));
$tableName = 'adTable';
$mimesis = new Mimesis($cwd, $tableName, 'ts_' . $tableName);
if($mimesis->lock()){
if(!$mimesis->tableExists()){
$mimesis->insertRow($adData);
}else{
$rowName = reset($mimesis->entries());
$rowName = str_pad($rowName, 3, '0', STR_PAD_LEFT);
$adData = array($rowName => reset($adData));
$mimesis->insertRow($adData);
}
}else{
trigger_error('Could not acquire lock on table', E_USER_ERROR);
}
$mimesis->release(); // Release the lock so other processes can affect the table
}
?>
Of course, that isn't enough. That only takes care of adding values into a database. We actually want to do something with those values (in this case display the ads). Thus we need the following code in another file (locking will not be necessary because we're not making any changes to the database):
ad.php
<?php
require_once('mimesis/Mimesis.php');
define('CURRENTWEEK', intval(date('W', time()))); // Establishes the current week
echo "Current week: " . CURRENTWEEK . "<br />"; // Prints the current week so we can see it
$cwd = realpath(dirname(__FILE__));
$tableName = 'adTable';
$mimesis = new Mimesis($cwd, $tableName, 'ts_' . $tableName);
// The query method is used in order to get all the row entries from a table
$adTableData = $mimesis->query();
// Assuming there's any data for the week then echo it to the browser
foreach($adTableData as $adTableValue){
if($adTableValue['week'] == CURRENTWEEK){
echo '<img src="' . $adTableValue['url'] . '" alt="' . $adTableValue['alt'] . '">';
}
}
?>