duan0818 2014-12-03 16:29
浏览 19
已采纳

Cakephp生成带有大写控制器名称的小写URL

I'm using Cakephp 2 I've been re factoring my code to use the Html->url() function instead of hard coding web addresses. For those not familiar, I pass a mixed $url variable containing controller and action names.

My gut tells me I should be defining the controller according to the file name and the action according to the function name inside the controller. ie: To route to AdminsController::index() I would say

$this->Html->url(array(
    'controller'=>'Admins'
    ,'action'=>'index'
));

and that SHOULD generate for me the url

http://example.com/admins/index

Unfortunately, what it is generating for me is

http://example.com/Admins/index

*notice the uppercase "A" in admins.

The purest in me refuses to identify the controller by its inflected name because then what's the advantage of using the url helper function at all? Why wouldn't I just write out the urls myself?

Shouldn't the url function be inflecting the controller names? Isn't lower case / camel case a part of the inflection process? Is there any way I can force this behavior?

Thanks

  • 写回答

2条回答 默认 最新

  • dqvy87517 2014-12-03 22:40
    关注

    If you define the following route in routes.php, you will then have your nice lowercase url :

    Router::connect('/admins/index', array(
        'controller' => 'Admins', 
        'action' => 'index'
    ));
    

    EDIT: other suggestion, you can also look into defining a custom route that would automatically lower case action and controller when parsing a route url: http://book.cakephp.org/2.0/en/development/routing.html#custom-route-classes

    EDIT2: just got an other idea. You can wrap Html helper into a custom one that performs what you want.

    In View/Helper/CustomHtmlHelper.php :

    <?php
    App::uses('HtmlHelper','View/Helper');
    
    class CustomHtmlHelper extends HtmlHelper {
    
    public function url($url = null, $full = false)
    {
        if(is_array($url)) {
            if(isset($url['controller']) {
                $url['controller'] = strtolower($url['controller']);
            }
            if(isset($url['action']) {
                $url['action'] = strtolower($url['action']);
            }
        }
        return parent::url($url, $full);
    }
    

    In Controller/AppController.php :

    public $helpers = array('Html' => array('className' => 'CustomHtml'));
    

    I haven't tested, so there might be errors in code. But this is the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料