PHP/OOP method overriding the DRY way

前端 未结 4 460
梦如初夏
梦如初夏 2021-01-14 10:15

I\'m curious if there is a \"better\" design for the following behavior:



        
4条回答
  •  广开言路
    2021-01-14 10:47

    There's no way in PHP to enforce this specifically;

    But, if Foo::foo must always execute before any subclass::foo, and you don't care about the results; perhaps the actual contents of the methods are badly designed.

    If you always must initialize something, perhaps you can do it in the constructor, if you're logging every call, perhaps you need a decorator.

    Here's another option that may work:

    class Foo {
    
      function doFoo() {
    
        // the code that 'must always run' goes here
        ...
        ...
        ...
        // and now we're calling the 'overridden' method.
        foo();
    
      }
    
      protected function foo() {
         // move along, nothing to see here
      }
    
    
    }
    
    class Bar extends Foo {
    
      protected function foo() {
         // Bar-specific foo stuff. 
      }
    
    }
    
    class Baz extends Foo {
    
      protected function foo() {
         // Baz-specific foo stuff. 
      }
    
    }
    

    The flaw here is that there's no 'multiple inheritance' or chaining.

    But yea, maybe you actually need some kind of pub-sub pattern.. or who knows?

    You're asking how you can implement your solution to a design problem, you should specifically ask how to solve your design problem.

提交回复
热议问题