PHP 动态与静态方法命名约定

PHP dynamic vs. static method naming convention

免责声明: 请参阅下面我更新的答案。本题中的代码是几种不良做法的示例,不应被模仿。

我正在尝试确定用于我的数据库派生 classes 的最佳命名约定。我经常 运行 遇到这样的情况,我希望同时拥有具有相似功能的静态和动态方法。

比如我有一家公司class。每家公司都有他们提供的各种产品。在我的公司中 class 我希望能够检索一家或多家公司提供的所有产品 ID,或者设置公司与产品之间的关联。

class Company {

     /** STATIC FUNCTIONS **/

     public static function GetProductIds($company_ids = array()){

          $company_ids = (array)$company_ids;

          // retrieve associated product ids from database

          return $product_ids;

     } // GetProductIds()


     public static function SetProductIds($company_ids = array(), $product_ids = array()){

          $company_ids = (array)$company_ids;
          $product_ids = (array)$product_ids;

          // insert company/product associations into database

          return true;

     } // SetProductIds()


     /** DYNAMIC FUNCTIONS **/

     public function ProductIds($product_ids = null){

          if($product_ids){
               return self::SetProductIds($this->company_id, $product_ids);
          }

          return self::GetProductIds($this->company_id);

     } // ProductIds()


} // CLASS Company

在此示例中,调用动态 ProductIds() 方法允许我使用相同的方法设置或获取数据。但是,我可能会遇到动态方法没有设置功能的情况。

有人对这是否是一个可接受的策略有建议吗?如果不是,您如何设置处理这些情况的方法?

更新: 我想我会更新这个答案,因为它获得了相当多的观点,而我原来的答案是……不好。 @Felippe Duarte 对我的问题的初步评论是绝对正确的。我将业务逻辑混合到我的所有模型中 类 并且过度使用静态方法和属性 waaaaaay 太多了。我现在尽量避免使用静态方法,将大的、广泛的 类 分解成多个 类 以考虑更具体的问题,并利用依赖注入在我的应用程序中重用服务。写这篇文章的时候我对框架没有任何经验,现在回过头来读还是很痛苦的哈哈。

原始(错误)答案:

我决定不这样设置我的 类。 Barmar 在他的评论中指出,我反对它的主要原因是动态方法的名称没有明确描述它的作用(因为它可以设置或获取)。我将把我的 get/set 方法分开以保持清晰。

Give your methods names that describe what they do. Don't worry about naming conventions for static vs. dynamic. Worry more about private vs. public -- does the method that saves to the DB really need to be public? It looks like it's an internal utility for the other methods. – Barmar

在命名需要基于多个 ID 获取数据的静态方法时,我还将使用类似 BulkGetProductIds() 的方法。