在PHP MVC中访问单例数据库对象时遇到问题

时间:2015-03-20 01:13:41

标签: php

我在访问PHP MVC中的单例类实例时遇到了麻烦。基本上MVC看起来像

enter image description here

首先,我在init.php中包含并实例化了对象

// include objects
include('app/Database.php');
include('app/models/m_template.php');
include('app/models/m_categories.php');

// create objects
$tdatabase = new Database();
$Template = new Template();
$Categories = new Categories();

并在m_categories.php我尝试将$tdatabase对象用作:

<?php

class Categories {

    private $db_table = 'category';

    function __construct() { }

    public function get_categories() {
        $data = array();
        $res = $tdatabase->query("SELECT * FROM " . $this->db_table . " ORDER BY name");

        foreach ($res as $dataRow):
            $data[] = array('id' => $dataRow['id'],
                'name' => $dataRow['name'],
                'img' => $dataRow['img'],
                'alt' => $dataRow['alt'],
            );

        endforeach;
        return $data;
    }
}

最后在index.php我有:

<?php
include('app/init.php');

echo '<pre>';
 print_r($Categories->get_categories());
echo '</pre>';

但是我遇到了以下错误:

enter image description here

你可以告诉我为什么会这样,以及如何解决这个问题?

更新1:

enter image description here

更新2

enter image description here

2 个答案:

答案 0 :(得分:1)

您的变量tdatabase超出范围。你需要将它传递给函数,或者在构造函数中将它设置为类成员变量,或者通过setter

public function get_categories(Database $tdatabase) {
        $data = array();
        $res = $tdatabase->query("SELECT * FROM " . $this->db_table . " ORDER BY name");

我经常看到这样的代码,我(几乎)总是建议,特别是对于使用模型/映射器模式的新项目,因为它更容易扩展,更易于维护。请看这里的例子:

OOP PHP PDO My First Project , Am I doing right?

答案 1 :(得分:1)

Categories对象没有关于外部变量的任何信息。您将Database对象传递给您的Categories对象,例如通过构造函数或方法参数。

的init.php

$tdatabase = new Database();
$Template = new Template();
$Categories = new Categories($tdatabase);

m_categories.php

class Categories {
    protected $database;
    private $db_table = 'category';

    function __construct($database) {
         $this->database = $database;
    }

    public function get_categories() {
        $data = array();
        $res = $this->database->query("SELECT * FROM " . $this->db_table . " ORDER BY name");
        // (...)
    }