我正在使用Yii2框架进行PHP开发。在我的视图文件中,如果我想调用任何函数,我只使用Class/Function
名称
例如:www.example.com/SiteController [class name] / index [function name]
它正在调用该函数。
我想知道,如何在纯PHP脚本中做同样的事情?
我在很多地方搜索过,我可以得到special_autoload_register();
的建议。但我无法理解确切的实际应用。
预计会有指导,谢谢你的到来。
答案 0 :(得分:2)
很容易:)。
它全部基于apache模块mod_rewrite。此模块允许您修改.htaccess文件中的路径行为。
使用此.htaccess文件
RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::$
RewriteRule ^(.*)$ - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
您将获得以下行为:
如果您被重定向到index.php,您可以在 $ _ SERVER [' REDIRECT_URL'] 或 $ _ SERVER [' REQUEST_URI& #39] 即可。在那里你可以接受,解析并根据要求的uri行事。
请以此作为解释文章,而不是如何实现这一目标的指南。大多数情况下,它需要一些apache配置,因为默认情况下大多数情况下都禁用了mod_rewrite。
如果你想要开展工作,我建议this post。
要完全回答您的问题,您可以举例说明" /"签收,将第一部分保存到$ firstPart,第二部分保存到$ secondPart,然后再保存
$controllerName = $firstPart."Controller";
$controller = new $controllerName;
$actionName = $secondPart."Action"
$response = $controller->$actionName();
因此,如果您致电/ help / me,将会调用 helpController-> meAction()。
我希望我帮助过。)
答案 1 :(得分:1)
为此,Yii 2(以及其他PHP框架)具有路由器。 Yii 2中的路由器是UrlManager类。
我不建议您从头开始编写路由器以获得要部署的解决方案。 PHP中有一些路由包,您可以在解决方案中轻松使用它们。我喜欢Klein。它是PHP中的纯路由器。
但是,如果出于学术目的,您想知道如何在PHP中使用路由,请了解$_SERVER
保留变量。它包含HTTP请求的所有详细信息。然后,您可以使用此处的详细信息来呼叫您要呼叫的特定功能。