dtnpf35197 2013-05-17 18:45
浏览 31

包括vs Extend用于数据访问

This is a design question that has irked me because deep down I know I'm doing it wrong. This is not necessarily just a PHP problem, but I'm working on a PHP project now so that's where I'm coming from. I'll just give you the scenario: I have a JSON generation class that is used by a data access script. Basically it's the go-to URL for a website that instantiates the JSONGen class, which in turn looks at a static file and pulls the data that was requested, and sends it back as a JSON object. The file that contains the raw data has it all in array format to allow for easier reading and updating (so one doesn't have to sift through raw JSON data and risk syntax error, etc). My question is in the accessing of that file. What I did was to place a require([json file]) outside the class definition. Everything in the [json file] is assigned to one $JSON object. In the class constructor, I do:

global $JSON;
$this->JSON = $JSON;

(Where $this->JSON is a private class variable).

This gives me access to the JSON from anywhere in the class, which is lovely. It feels hacky, but I can't find anything anywhere that addresses this specific type of approach.

The problem is that once somebody decides to move the class or whatever, the only way they have of understanding the dependency of this file is in that there's a require statement in the header. Is that just how things work? Or is there a better way to do this?

Should I use extend and put the JSON into a class (THAT sounds really stupid to me), or continue forward with my include? Or should I never, ever include a file in a class like this and rather pass it to the constructor or some other access method?

This specific instance is a small project, and it just doesn't make sense to set up a DB for it. We can add to the file, modify the config, and the whole site updates.... so please don't tell me to switch to a DB- I'm looking for strategies for this specific problem in a more general sense.

Thanks!

  • 写回答

1条回答 默认 最新

  • douxian7534 2013-05-17 19:11
    关注

    Probably going to get downvoted for this one but here it goes...

    class JSON_Response {
          public static $JSON;
    
          // don't let people make one of these it gives the illusion that there can be more then one
          protected function __construct(){}
    }
    

    then in your file

    JSON_Response::$JSON = $json;
    

    and access if from anywhere as JSON_Response::$JSON;

    and if there is anything that you commonly do to the json object (check a flag or something) you can just add a static method to the JSON_Response class.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大