リンクの前にこれを使用していない場合: http://altorouter.com/
小さなアプリケーションを作成していますが、フレームワークは必要なく、ルーティング部分のみが必要です。とてもシンプルに思えたので、altorouter を試してみることにしました。
特定のことをするために特定のルートをマッピングしたい。例えば:
www.example.com/products/
これにより、products.php テンプレートが表示され、データベースからデータを取得してフィールドに入力する必要があります。私はこれを次のように動作させました:
$router->map( 'GET', '/products', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getProductsContent($conn); //prepare all the page content from database
require __DIR__ . '/products.php'; //require the template to use
});
他のすべての標準ページでも同じですが、私の問題はルートがいつ変更されるかです。例えば:
www.example.com/shoes/
www.example.com/shorts/
www.example.com/shirts/
www.example.com/ties/
ユーザーがこれらのルートに移動したときに、「靴」というパラメーターを取得し、products.php テンプレートを使用しながら、靴のみのロジックを実行します。
したがって、ドキュメントを見ると、次のことができると書かれています。
www.example.com/[*] //これは何でも意味します。
ただし、これをリストされたルートに追加すると、ユーザーがアクセスしようとするものはすべて無効になります。彼らが訪問した場合:
www.example.com/products // 以前は機能していたように
実際には内部でロジックを実行します:
www.example.com/[*]
誰かaltorouterを知っていて、私を助けてくれませんか? 以下にページ全体のコードを貼り付けます。
// Site Router
$router->map( 'GET', '/', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getHomeContent($conn);
require __DIR__ . '/home.php';
});
$router->map( 'GET', '/products', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getProductsContent($conn);
require __DIR__ . '/products.php';
});
$router->map( 'GET', '/[*]', function($id) {
require('partials/connectdb.php'); //Require Database Connection
$test = 'this was a test';
$pageContent = getProductsContent($conn);
require __DIR__ . '/products.php';
});
// match current request url
$match = $router->match();
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}