如何 factoring/group php 方法

how to factoring/group php methods

我有一个 PHP class,其中包含不同的方法:

namespace App\Controllers;

class SuperAdminController extends Controller {

  public function name1Action($wanted = ''){
    $o = new name1Controller();
    self::routeWanted($wanted,$o,$this);
  }
   ...
  public function name10Action($wanted = ''){
    $o = new name10Controller();
    self::routeWanted($wanted,$o,$this);
  }

  private function routeWanted($wanted,$o,$that){
    switch($wanted){
      do something...
    }
  }

}

如何将我的所有 public 函数组合为一个函数,如

public function name1Action ... name10Action($wanted = ''){
    $o = new name1Controller();
    self::routeWanted($wanted,$o,$this);
} 

你可能想要 __call Magic.

class SuperAdminController extends Controller {

    public function __call($name, $args){
        // list of method names
        $mNames = [
            'name1Action' => 1,
            'name2Action' => 2,
            'name3Action' => 3,
            /* ... */
        ];
        if (isset($mNames[$name])) {
            $o = new {$name}();
            return $this->nameAction($args[0], $o);
        }
    }

    protected function nameAction($wanted = '', $o){
        self::routeWanted($wanted,$o,$this);
    }
}

你可以使用可变变量来解决这个问题:

function Action($controller, $wanted = '') {
    $c = "{$controller}Controller";
    $o = new $c();
    // ...
}

那么你可以使用:

$s = new SuperAdminController();
$s->Action('name1');

Demo on 3v4l.org

像下面这样更改您的代码:

namespace App\Controllers;

class SuperAdminController extends Controller {

//    public function name1Action($wanted = ''){
//        $o = new name1Controller();
//        self::routeWanted($wanted,$o,$this);
//    }
...
//    public function name10Action($wanted = ''){
//        $o = new name10Controller();
//        self::routeWanted($wanted,$o,$this);
//    }

    public function beforeRouteWanted($wanted, $number) {
        $class = 'name' . $number . 'Controller';
        $o = new $class();
        self::routeWanted($wanted, $o, $this);
    }

    private function routeWanted($wanted,$o,$that){
        switch($wanted){
        do something...
        }
    }

}