简体   繁体   English

如何实现从Rails到PHP的“匹配”路径概念?

[英]How to implement the “match” path concept from Rails into PHP?

In particular I have the following in the app's config/routes.rb file: 特别是我在应用程序的config / routes.rb文件中具有以下内容:

match "/:id" => "UrlDB#userreq"

And in the UrlDBController is: 在UrlDBController中是:

def userreq
    @request = UrlDB.find_by_url( (params[:id] )
end

I would like to be able to have the same userreq method respond to all incoming requests regards of what the :id value is - I don't know how to implement this in PHP/Apache. 我希望能够使用相同的userreq方法响应所有传入的请求,以了解:id值是什么-我不知道如何在PHP / Apache中实现它。

-daniel 丹尼尔

PHP gives you freedom about it. PHP为您提供了自由。 You are not forced to use "some concept of routing" (like in Rails), you can use "any concept of routing". 您不必强迫使用“路由的某些概念”(例如在Rails中),可以使用“路由的任何概念”。 You are not even forced to use "controller" nor the MVC model. 您甚至没有被迫使用“控制器”或MVC模型。

Simply get incoming parameters (using $_REQUEST), and decide "routing" by your own. 只需获取传入参数(使用$ _REQUEST),然后自行决定“路由”。

Or - use any existing framework - most of them define some "routing" template/engine. 或者-使用任何现有框架-大多数框架定义一些“路由”模板/引擎。

First, Rails is a Ruby framework, and PHP is a language. 首先,Rails是一个Ruby框架,而PHP是一种语言。 To get the same functionality in PHP you have to use a framework, as you do with Ruby. 要在PHP中获得相同的功能,您必须像使用Ruby一样使用框架。

Or you can do it by hands: 或者您可以手动完成:

The old way of doing this without using any framework, is by using Apache rewrite rules: 不使用任何框架的旧方法是使用Apache重写规则:

RewriteEngine On
RewriteRule /(\d+) userreq.php?id=$1

An other way is to do this manually in PHP, still with some help from Apache. 另一种方法是在PHP的帮助下手动完成此操作,仍然需要Apache的帮助。

In Apache config / .htaccess: 在Apache config / .htaccess中:

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . - [L]

And in index.php: 并在index.php中:

$path = $_SERVER['REQUEST_URI'];

if (preg_match('#/(\d+)#', $path, $match)) {
    // execute userreq controller
} else if (preg_match(...)) {
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM