doude1917 2012-06-21 18:11
浏览 26
已采纳

具有共同祖先冗余的PHP抽象对象设计

I helped design and implement and Droid API written in PHP. Though it works just fine, I am always looking to refactor my code.

Is it ok to have objects within other objects that have a common ancestor?

This may be an elementary question, but I can't seem to find information to support whether or not this is poor practice.

The goal is to have class foo provide common constants and methods to all.

Example:

            abstract class foo {
             //constants
             //common methods to all
            }

            class bar extends foo{
             //represents something
            }

            class widget extends foo {
             //represents something else
            }

            class controller extends foo{
                //controls flow
                public function __construct(){
                    $this->my_bar= new bar();
                    $this->my_widget= new widget();
             }
            }

Classes bar and widget may not need to extend foo, but methods within those objects wouldn't know about the common things that foo knows without sending parameters.

There seems to be too much redundancy going on, just looking for a best-practice.

  • 写回答

2条回答 默认 最新

  • dtqu72830 2012-06-21 18:20
    关注

    Creating a framework requires lots and lots of tries that will make you fall and then get back up on your feet.

    The most important thing about your question is to make sure you dont fall into the trap that the Liskov substitution principle describres:

    “If it quacks like a duck and looks like a duck but need batteries, it could be a duck but it probably isn’t.”

    The Liskov principle is simple, make sure that when you extend something, you are not changing the contract of the class. If a class used to return something on a function and you extend it to return something radically different, how will the user know how to adapt? You are defeating the purpose of reusability because you are providing a class that identifies as the base class it extends, but it doesn’t behave like the base class with added functionnalities.

    What i suggest the most is that you always try to make your class hierarchy as realistic as possible but remember the SOLID principle at all times. For more information on SOLID, look at my blog at:

    http://crazycoders.net/2012/03/confoo-2012-make-your-project-solid/

    Good luck

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算