drdzpknk76046 2018-06-29 11:18
浏览 101
已采纳

具有太多构造函数参数的PHP模型

In my current project I am implementing an Model-View-Presenter pattern. Most of my classes that represent domain objects have too many constructor arguments. Take this for example (NOTE: This is just a made-up class, just assume that models need too many arguments):

class Person {
    private $id;
    private $first_name;
    private $middle_name;
    private $last_name;
    private $birthdate;

    private $school_name;
    private $school_year_level;

    ... more properties

    public function __constructor($id, $first_name, $middle_name, $last_name, .. etc){
        ... some code to set the properties
    }
}

Suppose this class has many independent values needed for construction (7+ values), what good design can I use? The values are fetched rows from a database.

EDIT: To provide additional info, my model has three layers:

  • Models (Value Objects): Just a domain object with properties, and probably some methods for minimal processing of data.
  • Data Access Objects: Communicates with the database. CRUD. Creates Model objects from fetched data.
  • Service Objects: Provides an interface for the rest of the business logic interacts with data from the database.
  • 写回答

2条回答 默认 最新

  • douwei2966 2018-06-29 11:30
    关注

    You could use an associative array:

    public function __construct($params){
        $this->id = $params['id'];
        // etc ...
    }
    

    Or the spread operator if you are using PHP 5.6+:

    public function __construct(...$params){
        $this->id = $params[0];
        // etc ...
    }
    

    If you are under PHP 5.6 use func_get_args():

    public function __construct(){
        $params = func_get_args();
    
        $this->id = $params[0];
        // etc ...
    }
    

    I would use the associative array solution because I prefer having the keys. Note that there are many other ways to solve your "issue" as @ivanivan said in his comment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂