how to build a good router for php mvc

前端 未结 4 1413
灰色年华
灰色年华 2021-02-03 14:55

I\'m experimenting with php mvc and I\'m stucked with the following issue. My request and router classes are really simple and I would like to extend theme to can handle contro

4条回答
  •  天涯浪人
    2021-02-03 15:38

    Since your Request class uses a URI segments approach for identifying controller, action and arguments, global variables such as $_GET or $_REQUEST are not taken into account from within your Request.

    What you need to do is to make some additions to your Request code. Specifically:

    Remove the line:

    $this->_args = (isset($parts[0])) ? $parts : array();
    

    And add the following:

    $all_parts = (isset($parts[0])) ? $parts : array();
    $all_parts['get'] = $_GET;
    $this->_args = $all_parts;
    

    This way, $_GET (ie variables passed via the url) variables will be available in the actions called, as they will be in $args (they will be available as $args['get'] actually, which is the array that holds the $_GET vars, so you will be able to have access to domain=example by using $args['get']['domain']).

    Ofcourse, you can add one more method in your Request class (e.g. query) that might look like that:

    public function query($var = null)
    {
        if ($var === null)
        {
            return $_GET;
        }
        if ( ! isset($_GET[$var]) )
        {
            return FALSE;
        }
        return $_GET[$var];
    }
    

    This way, you can get a single variable from the url (e.g. $request->query('domain')) or the whole $_GET array ($request->query()).

提交回复
热议问题