how to factoring/group php methods

102 views Asked by At

I've got a PHP class which contains different methods:

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...
    }
  }

}

How can I group all my public function as one function like

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

There are 3 answers

1
Sherif On BEST ANSWER

You probably want __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);
    }
}
2
Nick On

You could use variable variables to solve this:

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

then you could use:

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

Demo on 3v4l.org

0
zymaozZ On

change your code like the below:

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...
        }
    }

}