一聚教程网:一个值得你收藏的教程网站

热门教程

Yaf框架自动添加URL后缀名例子

时间:2022-06-25 00:51:13 编辑:袖梨 来源:一聚教程网

同Codeigniter一样,Yaf也设置了几个钩子函数,在适当情况下可以接管或改变程序走向。

1routerStartup在路由之前触发这个是7个事件中, 最早的一个. 但是一些全局自定的工作, 还是应该放在Bootstrap中去完成
2routerShutdown路由结束之后触发此时路由一定正确完成, 否则这个事件不会触发
3dispatchLoopStartup分发循环开始之前被触发
4preDispatch分发之前触发如果在一个请求处理过程中, 发生了forward, 则这个事件会被触发多次
5postDispatch分发结束之后触发此时动作已经执行结束, 视图也已经渲染完成. 和preDispatch类似, 此事件也可能触发多次
6dispatchLoopShutdown分发循环结束之后触发此时表示所有的业务逻辑都已经运行完成, 但是响应还没有发送


通过钩子的定义可以看到,routerStartup是在路由初始化之前的钩子,所以可以在routerStartup中对REQUEST_URI后缀进行控制,有特定后缀时截取掉即可。
示例如下:

# applicationpluginsSystem.php

# Yaf_Registry::get('config')->application->url_suffix为配置文件定义的后缀,如:.html

 

class SystemPlugin extends Yaf_Plugin_Abstract

{

    public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response)

    {

        if(Yaf_Registry::get('config')->application->url_suffix) {

            if(strtolower(substr($_SERVER['REQUEST_URI'], - strlen(Yaf_Registry::get('config')->application->url_suffix))) == strtolower(Yaf_Registry::get('config')->application->url_suffix)) {

                $request->setRequestUri(substr($_SERVER['REQUEST_URI'], 0 , - strlen(Yaf_Registry::get('config')->application->url_suffix)));

            }

        }

    }

}

此处URL通过REQUEST_URI获取,其他方式同理。然后使用页面统一创建URL的方法,生成URL的时候加上后缀即可。

URL Rewrite的实现 .htaccess



RewriteEngine on

 

# if a directory or a file exists, use it directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

 

# otherwise forward it to index.php

RewriteRule . index.php

SAE

- rewrite: if (!is_file() && !is_dir() && path ~ "^/(.*)") goto "index.php/$1"

 

热门栏目