基于URL的加载方法

时间:2012-10-28 16:39:08

标签: php model-view-controller class methods

我正在尝试构建一个基于mvc的小应用程序。

如何根据查询字符串调用类中的方法?

例如,$ _GET查询字符串被设置为load_master_form

http://www.domain.com/settings/load_master_form

要在设置类中调用该方法,我正在做:

function __construct(){
    $this->{$_GET['method']}();
}

但显然这不起作用 - 加载这样的方法是不可能的。那怎么办呢?

3 个答案:

答案 0 :(得分:1)

我认为只要您为$ _GET ['method']创建了方法,并使用URI路由(.htaccess或其他)

,这样就行了。

通常我倾向于在URI中调用方法名 -

// domain.com/class_name/method_name/params

class class_name{
    function __construct(){
        ...
    }
    function method_name(){
        ...
    }
// etc.
}

答案 1 :(得分:0)

首先,您必须创建和.htaccess文件,以将所有请求重定向到单个文件(通常是index.php)。然后,用户输入的字符串将作为 GET 变量传递给php。

如何创建.htaccess文件here

然后你必须决定你MVC的结构。假设您希望url(http://www.someting.com/first/second/third)中的每个第三个参数都是一种方法。然后你会做这样的事情..

// Variables
$args = explode('/',$_GET['method']);

// Get method
$method = rtrim($args[1]);

这只是一个愚蠢的解决方案..

答案 2 :(得分:0)

我会像这样使用反射:

public static function doUserMethod($methodName)
{
    $reflectionMethod = new ReflectionMethod('YourUserMethodsClass', $methodName);
    return $reflectionMethod->invokeArgs(new YourUserMethodsClass(), array(/* Method Arguments Here */));
}

然后可以将其称为:

YourClass::doUserMethod($_GET['method']);

这样做的好处是,您可以将用户限制为仅指定您指定的特定类中的方法(例如,在我的示例中为YourUserMethodsClass)。显然,如果您的方法需要参数,则需要一些特殊的额外处理(与您给出的示例不同)。

相关问题