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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果