嗯,我是PHP的OOP的新手,並試圖用它編寫一個站點。該網站是一個基本的Flash遊戲網站,並有類別來跟蹤遊戲。我的第一步是創建一個基本的MVC設置並列出所有類別。問題是我不知道如何創建一個包含所有類別的數組。我可以將其添加到控制器嗎?我應該在模型中添加一個新方法嗎?讓我知道,代碼如下。如何創建特定對象的數組?
的index.php(控制器)
<?php
require_once 'database.php';
require_once 'models/category.php';
if (isset($_GET['page']))
{
}
else
{ //display home page
require_once 'views/home.php';
}
?>
模型/ category.php(模型)
<?php
class Category
{
private $id,$name;
function __construct($id)
{
$category_query = $database_connection->prepare('SELECT id,name FROM categories WHERE id=?');
$category_query->execute(array($id));
$category = $category_query->fetch();
$this->id = $category['id'];
$this->name = $category['name'];
}
function get_id()
{
return $this->id;
}
function get_name()
{
return $this->name;
}
}
?>
視圖/ home.php(視圖)
List of all categories:
<ul>
<?php foreach ($all_categories as $category) { ?>
<li><?php echo $category->get_name(); ?> (ID: <?php echo $category->get_id(); ?>)</li>
<?php } ?>
</ul>