2010-05-26 45 views
0

我为客户创建了一个基本类。访问类中的数组集合的最佳实践

我以前没有这样做,想知道访问数据的最佳方式。

对于客户数组中的每个字段,我是否应该有一个get()方法,或者我应该简单地将客户数组传回并访问该页面。

即刚好返回数组

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    $this->customer = mysql_fetch_row($query); 
    } 

    public function get_customer() { 
    return $this->customer; 
    } 
} 

与阵列中创建的每个项目的方法

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    $this->customer = mysql_fetch_row($query); 
    } 

    public function get_customer_name() { 
    return $this->customer->customer_name; 
    } 

    ... 

    ... 
} 

与基于Tobias的反馈选项3:(如果不知道语法是正确的)

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    return $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    return mysql_fetch_row($query); 
    } 
} 

回答

1

我会说最好只返回一个数组的所有数据,而不是仅仅为每个字段创建逻辑。它可能会经常发生,你需要更多的一个领域,并为此调用不同的方法会很烦人。

1

拥有一套功能默认情况下,返回的数据 - 没有坏处做,如果你总是我们e之后的数据。

+0

托比亚斯,作为一个新手,我可以通过改变以下几行来达到你的建议吗? 旧:$ this-> set_customer(); new:return $ this-> set_customer(); AND old:$ this-> customer = mysql_fetch_row($ query); new:return mysql_fetch_row($ query); – 2010-05-27 01:30:18

+0

是的,那应该工作:) – Tobias 2010-05-27 18:10:56

0

在我看来,后一种方法是更好的,你得到一个关于客户的所有信息,从不同的是第一种方法,你只使用该行所有在你的项目中返回客户行和那里的类中得到客户的详细信息。

0

有get_和set_方法的好处是你可以让这个类更聪明。使用类的视图编码器不能将变量设置为无效值,因为类知道有效值是什么并且可以返回错误。您可以为每个字段添加valid_方法,以允许视图编码器查看结果是否有效。您最终得到更好,更一致的数据。