I was coding a site in Php and needed to display announcements and needed a quick and simple way to do this. Moreover, I wanted to keep the design in the good ole MVC pattern. I know that there are examples out there utilizing PEAR and smarty templates. In fact, I am looking at
one now by Joe Stump. However, Joe's example MVC framework is on Php 5 and the server from my shared hosting provider has 4.3 on it. Any way, I wanted at least to separate the model and the view in some small way for easier modifications down the road.
Below is code that I wrote to act as an data access layer. Here I am using a text file as the persistence store for data.
Any feedback to
mark@msquaredweb.com is appreciated.
<?php
class AnnouncementsData{
var $announcements = array();
var $dataFile = "";
function AnnouncementsData(){
$this->dataFile = realpath("./") . '/pathToFileHere';
}
function getAnnouncements(){
//read the file into an array and add to the
//announcements collection
$data = file($this->dataFile) or die('...Check back soon.');
// loop through array and print each line
foreach ($data as $line) {
$announcements[] = $line;
}
//do not return duplicate announcements
return array_unique($announcements);
}
}
?>
Next, is the Announcement class. As you can see below, I have three attributes. In this example, I am using only the text attribute.
The Announcements class, that will hold an array of Announcement objects is next. This class also involves the data access layer via the AnnouncementsData class.
<?php
require "announcementsData.php";
require "announcement.php";
class Announcements{
var $announcements = array();
function Announcements(){
}
function getAnnouncements(){
$theAnnouncementsData = new AnnouncementsData();
foreach ($theAnnouncementsData->getAnnouncements() as $anAnnouncement){
$announcement = new Announcement();
$announcement->text = $anAnnouncement;
$announcements[] = $announcement;
}
return $announcements ;
}
}
?>
<?php
//get the announcements class
require 'classes/announcements.php';
//declare and instantiate an announcements object
$announcements = new Announcements();
//get the array of announcement objects
$announcementsArray = $announcements->getAnnouncements();
// loop through the announcement array and print each line
foreach ($announcementsArray as $annoucement) {
echo $annoucement->text . "<hr>";
}
?>
Even though we do not have a true controller, we have a separation of the model (data in a text file) from the view (in the include file above) by the business logic of the Announcement and Announcements classes.