PHP/OOP method overriding the DRY way

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

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



        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 10:55

    As long as you're overwriting your methods in subclasses, there is no way in any language I know of to enforce the behavior of the parent's method. If you're writing code just for your app, you should be able to trust your own code to call parent::foo(). But if you're writing a library, framework or API that others will build on, there is value to your idea. Ruby on Rails makes good use of that kind of behavior using callbacks.

    Okay, so don't define any foo methods. Instead, use __call and an array of closures as callbacks. My PHP is really rusty, so I forget some of the specifics.

    class Foo {
      // I forget how to make a class variable in PHP, but this should be one.
      // You could define as many callback chains as you like.
      $callbacks = array('foo_callback_chain' => []);
    
      // This should be a class function. Again, forget how.
      function add_callback($name, $callback) {
        $callbacks[$name.'_callback_chain'][] = $callback;
      }
    
      // Add your first callback
      add_callback('foo', function() {
        // do foo stuff
      })
    
      def method__call($method, $args) {
        // Actually, you might want to call them in reverse order, as that would be more similar
        foreach ( $callbacks[$method_name.'_callback_chain'] as $method ) {
          $method();
        }
      }
    }
    

    Then in your child classes, just append more callbacks with ""add_callback". This isn't appropriate for everything, but it works very well in some cases. (More about closures at http://php.net/manual/en/functions.anonymous.php.)

提交回复
热议问题