Manage URL routes in own php framework

前端 未结 12 2159
盖世英雄少女心
盖世英雄少女心 2021-02-02 16:34

I\'m creating a PHP Framework and I have some doubts...

The framework takes the url in this way: http:/web.com/site/index

It takes the first paramet

12条回答
  •  猫巷女王i
    2021-02-02 17:11

    I don't use OOP, but could show you some snippets of how I do things to dynamically detect if I'm in a subdirectory. Too keep it short and to the point I'll only describe parts of it instead of posting all the code.

    So I start out with a .htaccess that send every request to redirect.php in which I splice up the $_SERVER['REQUEST_URI'] variable. I use regex to decide what parts should be keys and what should be values (I do this by assigning anything beginning with 0-9 as a value, and anything beginning with a-z as key) and build the array $GET[].

    I then check the path to redirect.php and compare that to my $GET array, to decide where the actual URL begins - or in your case, which key is the controller. Would look something like this for you:

    $controller = keyname($GET, count(explode('/', dirname($_SERVER['SCRIPT_NAME']))));
    

    And that's it, I have the first part of the URL. The keyname() function looks like this:

    /*************************************
     *  get key name from array position
     *************************************/
    function keyname ($arr, $pos)
    {
        $pos--;
        if ( ($pos < 0) || ( $pos >= count($arr) ) )
              return "";  // set this any way you like
    
        reset($arr);
        for($i = 0;$i < $pos; $i++) next($arr);
    
        return key($arr);
    }
    

    To get the links pointing right I use a function called fixpath() like this:

    print 'link';
    

    And this is how that function looks:

    /*************************************
     *   relative to absolute path
     *************************************/
    function fixpath ($path)
    {
        $root = dirname($_SERVER['SCRIPT_NAME']);
        if ($root == "\\" || $root == ".") {
            $root = "";
        }
        $newpath = explode('/', $path);
        $newpath[0] .= $root;
        return implode('/', $newpath);    
    }
    

    I hope that helps and can give you some inspiration.

提交回复
热议问题