PHPでPATH_INFOを解析するクラス

こんな感じで良いでしょうか?

class PathInfo {
function __construct($args = null) {
 $this->args = parse_args(
  array(
   'path_info' => $_SERVER['PATH_INFO'],
   'separator' => '-',
   'delimiter' => '/'
  ), $args
 );
 $this->params = array();
 $this->args['path_info'] = preg_replace('/^\x2f/', '', $this->args['path_info']);
 $this->args['path_info'] = preg_replace('/\x2f$/', '', $this->args['path_info']);

 if (!empty($this->args['path_info'])) {
  foreach (explode('/', $this->args['path_info']) as $p) { 
   preg_match('/^([^-]+)-(.*?)$/', $p, $m);
   $this->init_param($m[1])->append_param($m[1],$m[2]);
   $m = null;
  }
 }
 return $this;
}

function param($key=null, $value=null) {
 if (empty($key)) return $this->params;
 if ($value === null) {
  if (isset($this->params[$key])) return $this->params[$key];
  else return null;
 }
 $this->init_param($key)->params[$key] = $value;
 return $this;
}

function append_param($key, $value) {
 $this->init_param($key);
 $this->params[$key] = array_merge($this->param($key), (array) $value);
 return $this;
}

function init_param($key) {
 if (!isset($this->params[$key])) $this->params[$key] = array();
 else {
  if (!is_array($this->params[$key])) $this->params[$key] = (array) $this->params[$key];
 }
 return $this;
}

} // END OF CLASS

parse_args は独自関数。

function parse_args($defaults, $args) {
 $a = array();
 $defaults = (array) $defaults;
 $args = (array) $args;
 foreach ($defaults as $k => $v) {
  $a[$k] = isset($args[$k]) ? $args[$k] : $defaults[$k];
 }
 return $a;
}

Leave a Reply