douyihuaimao733955
2017-04-27 13:35
浏览 54
已采纳

在Laravel的两个模型中使用单一方法; OOP PHP

I have 4 models held together by 4 pivot tables:

User, Company, Phone, Address

The User and Company are both tied together to Phone with the pivot tables user_phone and company_phone.

User has a method: addDefaultPhone( Request $request ). It grabs $request->input() and creates a phone number and attaches it to the User.

The same exact method can be used in the Company class. How can I include addDefaultAddress to both classes (without copying and pasting of course)?

图片转代码服务由CSDN问答提供 功能建议

我有4个模型由4个数据透视表组合在一起:

用户, 公司,电话,地址

用户和公司都使用数据透视表user_phone和company_phone绑定到Phone。

用户有一个方法: addDefaultPhone(Request $ request)。 它抓取 $ request-> input()并创建一个电话号码并将其附加到用户。

公司可以使用相同的方法 类。 如何将addDefaultAddress包含在这两个类中(当然不复制和粘贴)?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanchigeng4313 2017-04-27 13:40
    已采纳

    You may use inheritance or trait. Choose whatever you want.

    Inheritance

    Create a base class:

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    
    class ThingWithAPhone extends Model {
        public function addDefaultPhone() {
            /* Whatever you want... */
        }
    }
    

    Then both User and Company could extend this class:

    // In the user file
    class User extends ThingWithAPhone { /* ... */ }
    
    // In the company file
    class Company extends ThingWithAPhone { /* ... */ }
    

    Trait

    Create a trait:

    namespace App;
    
    class Phonable {
        public function addDefaultPhone() {
            /* Whatever you want... */
        }
    }
    

    Use this trait:

    // In the user file
    class User extends Model { 
        use Phonable;
        /* ... */ 
    }
    
    // In the company file
    class Company extends Model {         
        use Phonable;
        /* ... */ 
    } }
    

    With trait you can create class which have X traits, and one other class with Y traits and some of these traits may be common to both classes.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题