PHP код:
<?php
/*****************************************************************************
* класс для работы с новостной лентой. автор - ss88 *
*****************************************************************************
*/
class newsList
{
protected $newsList,//массив со всеми выбранными новостями
$xDoc,//xml-документ
$newsNodeList,
$newsCount,//количество новостей в базе
$newsPerPage,//кол-во новостей на страницу
$fileName,//имя файла базы
$maxId;//максимальный из присутствующих идентификаторов
//конструктор
function __construct($filename,$newsPerPage)
{
if(file_exists($filename))
$this->xDoc=new DOMDocument();
else
echo "Ошибка открытия файла";
$this->newsPerPage=$newsPerPage;
$this->fileName=$filename;
//открыть базу
$this->xDoc->load($this->fileName);
$this->xDoc->formatOutput=TRUE;
//получить корневую часть
$this->newsNodeList=$this->xDoc->getElementsByTagName("newsItem");
//чтение и инициализация
$this->initRead();
}
//получить весь список новостей
function getAllNews()
{
return $this->newsList;
}
//получить новость по идентификатору
function getById($id)
{
if($this->newsCount<1)
return NULL;
else
{
foreach($this->newsList as $oneItem)
if($oneItem['id']==$id)
return $oneItem;
return NULL;
}
}
//получить страницу
function getPage($pageNum)
{
if(($this->newsCount - $this->newsPerPage*($pageNum-1))>0)
{
$arPage=array();
for($i=$this->newsPerPage*($pageNum-1);isset($this->newsList[$i])&&($i<$this->newsPerPage*($pageNum-1)+$this->newsPerPage);$i++)
array_push($arPage,$this->newsList[$i]);
return $arPage;
}
else
return NULL;
}
//редактировать новость
function editItem($id,$bind)
{
if($item=$this->getById($id))
{
for($i=0;$i<$this->newsNodeList->length;$i++)
if(($this->newsNodeList->item($i)->childNodes->item(0)->nodeValue)==$id)
{
$oldNode=$this->newsNodeList->item($i);
if($i!=$this->newsNodeList->length-1)
$nextNode=$this->newsNodeList->item($i);
break;
}
$newNode=$this->makeNewNode($bind,$id);
$bigNode=$this->xDoc->getElementsByTagName("newsList")->item(0);
$bigNode->replaceChild($newNode,$oldNode);
$this->xDoc->save($this->fileName);
$this->initRead();
return $this->getById($id);
}
else
return NULL;
}
//добавить новость
function addItem($bind)
{
if(!is_array($bind))
return NULL;
else
{
$newNode=$this->makeNewNode($bind);
$bigNode=$this->xDoc->getElementsByTagName("newsList")->item(0);
$bigNode->appendChild($newNode);
$this->xDoc->save($this->fileName);
$this->initRead();
return $this->getById($this->maxId);
}
}
//удалить новость
function removeItem($id)
{
if($this->getById($id))
{
for($i=0;$i<$this->newsNodeList->length;$i++)
if(($this->newsNodeList->item($i)->childNodes->item(0)->nodeValue)==$id)
{
$delNode=$this->newsNodeList->item($i);
break;
}
$bigNode=$this->xDoc->getElementsByTagName("newsList")->item(0);
$bigNode->removeChild($delNode);
$this->xDoc->save($this->fileName);
}
else
return FALSE;
}
//сервисная защищенная функция для формирования nod'а
protected function makeNewNode($bind,$id=-1)
{
$newNode=$this->xDoc->createElement("newsItem");
$newNode->appendChild($this->xDoc->createElement("id",($id==-1)?($this->maxId+1):$id));
$newNode->appendChild($this->xDoc->createElement("name",$bind['title']));
$newNode->appendChild($this->xDoc->createElement("shortDescription",$bind['description']));
$newNode->appendChild($this->xDoc->createElement("extDescription",$bind['extDescription']));
$newNode->appendChild($this->xDoc->createElement("pictureFile",$bind['picture']));
$newNode->appendChild($this->xDoc->createElement("date",$bind['date']));
return $newNode;
}
//защищенная ф-ция. чтение и инициализация, всего, что связано с новостями
protected function initRead()
{
$this->newsList=array();
if(!$this->newsNodeList->length)
return;
else
{
$this->maxId=-1;
for($i=0; $i<$this->newsNodeList->length;$i++)
{
$xItem=$this->newsNodeList->item($i);
if($this->maxId<$xItem->childNodes->item(0)->nodeValue)
$this->maxId=$xItem->childNodes->item(0)->nodeValue;
$oneItem=array
(
"id"=>$xItem->childNodes->item(0)->nodeValue,
"title"=>$xItem->childNodes->item(1)->nodeValue,
"description"=>$xItem->childNodes->item(2)->nodeValue,
"extDescription"=>$xItem->childNodes->item(3)->nodeValue,
"picture"=>$xItem->childNodes->item(4)->nodeValue,
"date"=>$xItem->childNodes->item(5)->nodeValue
);
array_push($this->newsList,$oneItem);
}
$this->newsCount=count($this->newsList);
}
}
}
?>
Вот такой вот примерчик работы с новостями без БД. Конечно, он сделан на скорую руку и оптимальностью не блещет, но пригоден для использования. Для оптимизации (если, например, разведется несколько тысяч новостей) можно для чтения файла использовать более шустрый, нежели DOM, интерфейся, благо, парочка таких альтернатив имеется + нужно уже будет вычитывать не всю базу, а кусками, потому что ресурсы сервера нихрена не резиновые.
xml
PHP код:
<?xml version="1.0"?>
<newsList>
<newsItem><id>1</id><name>Edited Name Of First Item 666</name><shortDescription>
short decription of the first item
</shortDescription><extDescription>
extended decription of the first item
</extDescription><pictureFile>
1.jpg
</pictureFile><date>10.10.1666</date></newsItem>
<newsItem><id>2</id><name>Edited Name</name><shortDescription>
short decription of the SECOND item
</shortDescription><extDescription>
extended decription of the SECOND item
</extDescription><pictureFile>
2.jpg
</pictureFile><date>10.11.1666</date></newsItem>
<newsItem><id>3</id><name>We wish to work well</name><shortDescription>
short decription of the first item
</shortDescription><extDescription>
extended decription of the first item
</extDescription><pictureFile>
1.jpg
</pictureFile><date>10.10.1666</date></newsItem>
</newsList>
Вот так выглядит сам файл с новостями
|