简体   繁体   中英

How do I pass a get variable through a url with a custom router?

I'm making a website using a custom made router. With the current code, I can add a pretty url for example '/contact' to the website. I'm now this far that I need to add a product page. Normally you would have a url like product?product_id=$product_id. But I don't know how I can implement this idea with the current code. The Route class is where is where it adds new urls.

class Route
{
    private $_uri = array();
    private $_method = array();

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');

        if($method != null){
            $this->_method[] = $method;
        }
    }

    public function submit()
    {

        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
        $routeFound = false;
        foreach($this->_uri as $key => $value){
            if(preg_match("#^$value$#",$uriGetParam)){
                if(is_string($this->_method[$key])){
                    $routeFound = true; 
                    $useMethod = $this->_method[$key];
                    new $useMethod();
                }
                else{
                    $routeFound = true; 
                    call_user_func($this->_method[$key]);
                }
            }
        }
        if(!$routeFound){ 
            http_response_code(404);
            require_once 'pages/404.php';
        }
    }

And in the index file i actually add routes to the project

<?php
  require_once 'classes/route.php';
  require_once 'classes/config.php';
  require_once 'classes/model.php';
  require_once 'functions.php';
  require_once 'classes/validator.php';

$route = new Route();
$db = new Db();
$model = new Model();

$route->add('/', function(){
  require_once 'pages/home.php';
});

$route->add('/product', function(){
  require_once 'pages/product.php';
});

$route->add('/contact', function(){
  require_once 'pages/contact.php';
});

$route->add('/admin', function(){
  require_once 'pages/admin.php';
});

$route->add('/login', function(){
  require_once 'pages/test.php';
});

$route->submit();

Which framework are you using? I'm learning CodeIgniter now, what I do there is something like:

the URL for product would be: application_path/controller/method/id For product: application_path/product/insert/1 (Using “1” as an ID example)

I'd have to add a route, in the route file, to specify that after my /method I'll have an ID. (I believe the way you do it depends on the framework you're using)

In my controller, my method would receive a parameter. Just like:

Public function insert($id){
//code...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM