You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CakePHP 1.3:如何通过控制器访问视图,使URL路由符合application/controller/view

实现CakePHP 1.3 URL路由符合application/controller/view格式的步骤

1. 给控制器添加对应Action方法

你的NamesController目前是空的,必须先定义对应视图的Action方法,CakePHP 1.3会自动匹配Action名对应的视图文件(位于app/views/names/目录下,文件名是action名.ctp)。

比如要访问application/names/index或application/names/view,需要添加对应方法:

class NamesController extends AppController {
    var $helpers = array ('Html','Form');
    var $name = 'Names';

    // 对应index视图,URL为 /application/names/index
    function index() {
        // 可在此传递数据到视图,例:$this->set('list', $someData);
    }

    // 对应view视图,URL为 /application/names/view
    function view() {
        // 业务逻辑代码
    }
}

同时要确保在app/views/names/目录下创建index.ctp和view.ctp视图文件。

2. 配置CakePHP核心参数

打开app/config/core.php,确认以下配置:

  • 路由功能默认开启,无需额外关闭;若不需要后台路由,保持Configure::write('Routing.admin', false);即可。
  • 如果应用部署在IIS的虚拟目录下(对应URL中的application部分),需要设置基础路径:
Configure::write('App.baseUrl', '/application');

若应用部署在根站点,则无需设置App.baseUrl。

3. 配置IIS的URL重写规则(去掉index.php)

CakePHP默认依赖index.php转发请求,要实现干净的application/controller/view格式,需在IIS中配置URL重写,将请求自动转发到index.php。

在应用根目录下创建web.config文件,添加以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="CakePHP Rewrite" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
        <defaultDocument>
            <files>
                <add value="index.php" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>

注意:若应用在虚拟目录下,需将action节点的url调整为/application/index.php/{R:1}。

4. 验证路由

完成配置后,即可通过以下URL访问对应视图:

  • 访问Names控制器的index视图:http://你的服务器地址/application/names/index
  • 访问Names控制器的view视图:http://你的服务器地址/application/names/view

若应用部署在根站点,URL则为http://你的服务器地址/names/index和http://你的服务器地址/names/view。

内容的提问来源于stack exchange,提问作者iamdeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 07:06:21