Search code examples
phpclassmethodsfactoring

how to factoring/group php methods


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);
} 

Solution

  • 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);
        }
    }