PHP-从数据库加载/删除是否使用静态方法


PHP - load/delete from DB use static methods or not?

请看一下这个类,我知道应用程序外部的一段代码告诉很少关于应该做什么,但我认为你基本上理解应该做什么和应该用来做什么。

<?php
class Customer
{
   const DB_TABLE = 'customers';
   public $id = NULL;
   //all other properties here
   function __construct($associative_array = NULL)
   { 
      //fills object properties using values provided by associative array
   }
   static function load($customer_id)
   {
      $obj = new static(); //PHP 5.3 we use static just in case someone in future wants to overide this in an inherited class
      //here we would load data from DB_TABLE and fill the $obj
      return $obj;
   }
   static function delete($customer_id)
   {
      //here we just delete the row in the DB_TABLE based on $customer_id (which is the primary key of the table)
   }
   function save()
   {
      //saves $this properties into a row of DB_TABLE by either updating existing or inserting new one
   }
}

除了你会对代码发表的任何类型的评论(我们总是很感激)之外,这里的主要问题是:"在so上读了这么多关于static方法有多糟糕,以及static的一般用法的文章后,在这个代码中,你会让load/delete这两种方法不是静态的吗?如果是,为什么,你能用一个小例子解释一下吗?"

对我来说,不让它们成为static似乎很奇怪,因为我认为创建一个从DB加载的新对象是很奇怪的,每次都要强制写入:

$obj = new Customer(); //creating empty object
$obj->load(67); //loading customer with id = 67

而不是简单地进行

$obj = Customer::load(67); //creates a new customer and loads data form DB

这一切都取决于您希望代码如何结构化。IMO静态功能还不错,只要你正确使用它们。

例如,我的所有模型功能都是相似的,并遵循以下结构:

class models_car {
    public static function getCar($id);
    public static function getCars();
    public static function getCarsByDriver(models_driver $driver);
    public function save();
    public function delete();
    public function isNew();
    public function getProperty1();
    public function getProperty2();
    public function getProperty3();
    public function setProperty1($value);
    public function setProperty2($value);
    public function setProperty3($value);
}

因此,在这里,您可以使用模型作为特定条目的表示,如果您调用delete或save,它将在对象本身的上下文中调用。如果您调用getCar、getCars或getCarsByDriver,它们是静态的,因为它们不属于特定的对象,它们是返回填充对象的加载器。

无论如何,这并不意味着这是最好的方法,但这是我多年来一直使用的方法,它已经被证明可以创建非常好和可管理的代码。