自定义mvc路由器在链接中有连字符问题

时间:2013-11-06 17:14:07

标签: php model-view-controller router

我已经为我的MVC编写了一个基本的路由器类,但是我在链接中使用连字符时遇到了麻烦,它为现有的链接提供了403 Forbidden,但是对于不存在的链接,它会正确打印出来并给出一个404错误页面。

我的控制器类的形式是Link_Here,我在路由器中将连字符更改为下划线。 URL结构为http://example.com/ {$ controller} /($ action)/($ parameters),问题是控制器部分

这是我的路由器代码:

    <?php

class Router
{
    private $url, $controller, $method, $params;
    private $allowedChars = array('-', '_', '/', '\\', '.');

    public function __construct()
    {
        if(!empty($_GET['page']))
        {
            if(ctype_alnum(str_replace($this->allowedChars, '', $_GET['page'])))
            {
                $this->url = $_GET['page'];
            }
            else
            {
                throw new Exception("Malformed URL");
            }
        }
        else
        {
            $this->url = 'index';
        }

        $this->url = explode('/', $this->url);

        // This is where I change the hyphen to an underscore
        $this->controller = implode('_', array_map('ucfirst', explode('_', str_replace('-', '_', array_shift($this->url)))));
        $this->method = array_shift($this->url);
        $this->params = &$this->url;
    }

    public function commit()
    {
        if(class_exists($this->controller))
        {
            if(method_exists($this->controller, $this->method) && empty($this->params))
            {
                if(empty($this->params))
                {
                    $ctrl = new $this->controller;
                    $ctrl->loadModel($this->controller);
                    $ctrl->{$this->method};
                }
                else
                {
                    $ctrl = new $this->controller;
                    $ctrl->loadModel($this->controller);
                    $ctrl->{$this->method}($this->params);
                }
            }
            else
            {
                $ctrl = new $this->controller;
                $ctrl->loadModel($this->controller . '_Model');
                $ctrl->index();
            }
        }
        else
        {
            $ctrl = new Error;
            $ctrl->loadModel('Error');
            $ctrl->notFound();
        }
    }
}

我的重写规则:

    <IfModule mod_rewrite.c>
    Options +FollowSymlinks
  # Options +SymLinksIfOwnerMatch
    Options -Indexes

    RewriteEngine On
    # RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
</IfModule>

0 个答案:

没有答案