.htaccessファイルに書き直し命令を書くことで、カスタム指示文を書きます。私のルートをより効率的にするには?
class Route {
public $request_url;
public $url_args;
public $request_method;
function __construct() {
$this -> request_url = $_SERVER['PATH_INFO'];
$this -> url_args = explode('/', substr($_SERVER['PATH_INFO'], 1));
$this -> request_method = $_SERVER['REQUEST_METHOD'];
}
public function get($url, $callback) {
if($this -> request_method == 'GET') {
if($url == $this -> request_url){
$callback();
} elseif(strpos($url, ':')) {
$new_url_args = explode('/', substr($url, 1));
if(count($new_url_args) == count($this -> url_args)) {
$match = true;
$args = [];
for($i = 0; $i < count($this -> url_args); $i++) {
if($new_url_args[$i][0] == ':') {
$args[substr($new_url_args[$i], 1)] = $this -> url_args[$i];
} else {
if($new_url_args[$i] != $this -> url_args[$i]){
$match = false;
break;
}
}
}
if($match) {
$callback($args);
}
}
}
}
}
}
次に、次のようにいくつかのルートを開始して追加しました。
$route = new Route();
$route -> get('/', function() {
echo "Welcome to DocsApp";
die;
});
$route -> get('/test/sample', function() {
echo 'tested';
die;
});
$route -> get('/user/:id/:name', function($args) {
echo $args['id'] . '<br />' . $args['name'];
die;
});
すべて正常です。
しかし、すべてのget関数は、必要な関数の代わりに呼び出しています。 これを防ぐため、一致するルートのコールバックが成功すると、die
がコールされます。
特定のルート機能を呼び出し、不要なコールを防止する方法はありますか?
ここをクリックしてください:https://github.com/noodlehaus/dispatchこのライブラリを使用することも、コードを見ることもできます。 –
リンクをありがとう。私はそれを試してみます。 – Harish