2016-11-30 13:56
浏览 161


I have a php object method that load object "A" with the following MySQL query:


I have another php object named B that uses MySQL fields from object A:


To prevent code repetition, would it be considered a good practice to create an array (or an object) that stores the MySQL fields names of Object A so that this array can be used in object A and object B, like this:

Object A MySQL loading:

SELECT '.implode(',', $mysql_a_fields).' '...

Object B MySQL loading:

SELECT '.implode(',', $mysql_a_fields).',,

Or would it be code smell?

The goal is to to prevent repeating some SQL fields along queries that use those SQL fields. For example, if there is a mysql date field for object A that I want to get formatted the same way in all the requests I use this date field, is there any design pattern to prevent repeating DATE_FORMAT(date_field) in all the request?

Thank you

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


  SELECT, ... 

我有另一个名为B的php对象,它使用来自对象A的MySQL字段 :

  SELECT, ..., 
 <  p>为了防止代码重复,创建一个存储对象A的MySQL字段名称的数组(或对象)是一个好习惯,这样就可以在对象A和对象B中使用这个数组,如下所示:  / p> 


  SELECT'.implode(',',$ mysql_a_fields)。'  '... 

对象B MySQL加载:

  SELECT'.implode(',',$  mysql_a_fields)。',, 


目标是防止在使用这些SQL字段的查询中重复某些SQL字段。 例如,如果对象A的mysql日期字段我希望在我使用此日期字段的所有请求中以相同的方式进行格式化,是否有任何设计模式可以防止在所有请求中重复DATE_FORMAT(date_field)? / p>


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

1条回答 默认 最新

  • doupeng6890 2016-11-30 16:19

    About that array of field names. I would not do it. If you need to write all your selects this way, than write them. I do not know enough about your class/project structure to say if this makes sense.

    To help you with your date formatting problem (well, it's not really a problem, isn't it), I think you have two options: 1. Get the date field from the database as is and convert it in PHP. (Use a helper class that is accessible from everywhere to do this.) 2. Create a stored procedure that converts the format for you and use this in your SELECT queries.

    解决 无用
    打赏 举报

相关推荐 更多相似问题