Citat:
Ursprungligen postat av Anaxa
Jag gjort det :P Eller vad mer ville du ha?
|
Det går inte att testköra koden, eftersom du saknar databasconnection, och testkod.
Gör en komplett Console app som går att testköra så kan du få mer hjälp. Annars måste jag bygga en helt egen app bara för att testköra detta .....
Du bör ju göra Category till en klass med metoder för add(), remove(), load()/fetchall(), save(), move(), delete()....
I klassen ska du ha en privat variabel som innehåller själva trädstrukturen, så det går att skapa fler instanser av klassen, om man nu vill göra det.
Du bör ha en helt egen klass som innehåller databasconnection och som man kan göra ett static anrop till för att få den eventuellt öppna Connection som finns till databasen. För varje tabell du har i databasen gör du (minst) en egen klass (ibland behövs fler klasser för en tabell om man har en komplex struktur). Connectionklassen kan då återanvändas mellan alla dessa tabellklasser, Connection är troligen samma för hela databasen (undantag finns).
PHP-kod:
// File: DBConnection.php
class DBConnection
{
protected $activeConnection;
static function getConnection()
{
/// Code goes here ....
}
}
PHP-kod:
// File: category.php
class Category
{
protected $categories = array();
// Initiate array of cateories on instance creation
function __construct()
{
$categories = array();
}
// Destruct activity when instance dies
function __destruct()
{
}
// Load all categories from datavbase to array in instance
function load()
{
$mainCategories = mysql_query("SELECT id, name FROM categories WHERE parent=0", getConnection());
while($ds = mysql_fetch_assoc($mainCategories))
{
$categories[] = array
(
"Name" => $ds["name"],
"Children" => GetChildren($ds["id"])
);
}
}
function GetChildren($parent)
{
$children = array();
$childCats = mysql_query("SELECT id, name FROM categories WHERE parent='".$parent."'");
while ($cat = mysql_fetch_array($childCats))
{
$children[] = array
(
"Name" => $cat["name"],
"Children" => GetChildren($cat["id"])
);
}
return $children;
}
// Add one category
function add()
{
}
// Delete one cateory and all sub categories
function remove()
{
}
// Move one category from one parent toi another
function move()
{
}
// Save all unsaved categories in memory to database
function save()
{
}
// Find category by name, and return ID
function find()
{
}
}
PHP-kod:
// File: categoryTest.php
// Testcode goes here
class CategoryTest
{
function __construct()
{
print "Test Starts now.\n"
$this->testAdd();
$this->testMove();
$this->testRemove();
$this->testSave();
$this->testLoad();
}
function testAdd()
{
print "Test of Add function.\n"
$testCategories = new Category();
$cat1 = $testCategories.add("Test1");
}
function testAdd()
{
}
function testMove()
{
}
function testRemove()
{
}
function testSave()
{
}
function testLoad()
{
}
function __destruct()
{
print "Test is Done.\n"
}
}
new categoryTest();