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

在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)?

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程