如何在MVC中获取$ _GET参数

时间:2017-05-07 16:34:15

标签: php .htaccess

提前告诉我的英语,伙计们。有一个MVC框架,制作一个网站。 .htaccess文件:

AddDefaultCharset utf-8

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
ErrorDocument 404 /404.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php

Router.php:

 class Router
{

    private $routes;

    public function __construct()
    {
        $routesPath = ROOT.'/config/routes.php';
        $this->routes = include($routesPath);
    }

// Return type

    private function getURI()
    {
        if (!empty($_SERVER['REQUEST_URI'])) {
        return trim($_SERVER['REQUEST_URI'], '/');
        }
    }

    public function run()
    {
        $uri = $this->getURI();

        foreach ($this->routes as $uriPattern => $path) {

            if(preg_match("~$uriPattern~", $uri)) {


                $internalRoute = preg_replace("~$uriPattern~", $path, $uri);

                $segments = explode('/', $internalRoute);

                //Search name for controller we need
                $controllerName = array_shift($segments).'Controller';
                $controllerName = ucfirst($controllerName);

                //Находим название action
                $actionName = 'action'.ucfirst((array_shift($segments)));

                $parameters = $segments;
                $controllerFile = ROOT . '/controllers/' .$controllerName. '.php';
                if (file_exists($controllerFile)) {
                    include_once($controllerFile);
                }
                $controllerObject = new $controllerName;
                $result = call_user_func_array(array($controllerObject, $actionName), $parameters);
                if ($result != null) {
                    break;
                }
            }
        }
    }
}

routes.php(控制器和路由的数组)

 <?php
return array(
    'admin/product/update/([0-9]+)' => 'adminProduct/update/$1',
    'admin/product/delete/([0-9]+)' => 'adminProduct/delete/$1',
    'admin/products/create' => 'adminProduct/create',
    'admin/products' => 'adminProduct/index',
    'admin' => 'admin/index',
    'login' => 'user/login',

    'product/([\w]{1,})' => 'product/view/$1',
    'category/([\w]{1,})' => 'site/category/$1',
    '([\s\S\w\W\d\D]{1,})' => 'site/error',
    '' => 'site/index/$1',
);

问题:$ _GET参数不起作用,因为Router.php无法在routes.php中搜索?asd=asd。 例如:链接site/?utm_sourse=vk不起作用,因为Router.php将其识别为'([\s\S\w\W\d\D]{1,})' => 'site/error'。在这种情况下,我该怎么做才能获得$ _GET参数?

1 个答案:

答案 0 :(得分:1)

我认为您可以更改Router::getURI()以在返回任何查询字符串之前将其删除。没有经过测试,但有些内容如下:

private function getURI()
{
    $uri = '';

    if (!empty($_SERVER['REQUEST_URI'])) {
        $uri = $_SERVER['REQUEST_URI'];
    }

    if (($cutoff = strpos($uri, '?')) !== false) {
        $uri = substr($uri, 0, $cutoff);
    }

    return trim($uri, '/');
}