【问题标题】:PHP - load/delete from DB use static methods or not?PHP - 从数据库加载/删除是否使用静态方法?
【发布时间】:2012-01-17 19:36:30
【问题描述】:

请看一下这个类,我知道应用程序之外的一段代码几乎没有说明应该做什么,但我认为你了解基本上应该做什么和用于做什么。

<?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
   }
}

除了您将在代码上制作的任何类型的 cmets(总是受到赞赏)之外,这里的主要问题是:“在 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

【问题讨论】:

    标签: php database static load


    【解决方案1】:

    这完全取决于您希望您的代码结构如何。 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);
    }
    

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

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

    【讨论】:

    • 让我们谈谈删除,你没有声明static。如果我使用您的代码怎么办:$obj = getCar(78); $obj-&gt;delete(); 我想这会在数据库中删除带有id = 78 的行,但是在删除之后$obj 中有什么?例如:如果删除后我调用$obj-&gt;save(); 会发生什么
    • @MarcoDemaio 我通常在我的对象中也有一个 RESET 函数,并且在 LOAD/DELETE 时会调用 reset。因此,该对象成为一个全新的实例。就像我说的那样,这不一定是最好的方式,但我喜欢它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多