问题
I want to setup HtmlHelper::link() method so the default options array have escape = false.
How can I achieve this without changing the core class?
OBS: I already sanitized form input, so I guess this will have no problem.
Thanks in advance.
回答1:
Cake 2.1.5
I just implemented this and I wanted to point out a few things:
Your custom html helper should extend HTML helper (and don't forget to include the HTML helper class)
App::uses('HtmlHelper', 'View/Helper');
class CustomHtmlHelper extends HtmlHelper {
//yadda yadda
}
Additionally, your call in AppController should not include the word Helper:
'Html'=> array('className' =>'CustomHtml'),
回答2:
In Cake 2.0
Create your OwnHelper class containing a link method, which extends HtmlHelper, in AppController specify:
$helpers = array('Html' => array('className' => 'OwnHelper'));
via ADmad
回答3:
Why don't you create your own custom helper and create a method that returns the HTMLHelper's link with the options set?
http://book.cakephp.org/view/102/Including-other-Helpers
class MyHelper extends AppHelper {
var $helpers = array('html');
function linkNoEscape($title, $url)
$options = array(); //set custom options, e.g. no escape
return $this->Html->link($title, $url, $options);
}
}
回答4:
I'm never comfortable overriding methods higher up in the hierarchy (ie in AppHelper) because there is always a good chance you break other helpers that are dependent.
Hoping to be able to comment soon, instead of giving rubbish half answers!
Also relevant: I heard that CakePHP 2.0 will allow helpers, components etc to be aliased. Eg you want to change the output from HtmlHelper, you can replace it with your own version without changing all your view templates.
回答5:
You could copy the original HTMLHelper
from cake/libs/view/helpers
to app/views/helpers
and modify the link()
method there.
回答6:
another good practice that I think cakephp should implement that you also can implement is a simple Factory Pattern Helper. The following should be consider just psuedo not real code.
$this->Factory->getHelper('Html')->link();
instead of
$this->Html->link();
take the following for example
class FactoryHelper extends Helper {
public function getHelper($name) {
if(Configure::read('Overrides.{$name}')) {
return $this->{Configure::read('Overrides.{$name}')};
}
return (isset($this->{$name})?$this->{$name}:false);
}
}
//Bootstrap is where you will set all your overrides
Configure::write('Overrides',array(
'Html'=>'NewHtml'
));
//so now when you want to override any helper you can
So now in the bootstrap that you set to override Html Helper. Throughout your entire site, your new 'NewHtml' helper will be called instead of the traditional helper.
回答7:
you can overwrite any helper method from AppHelper, so
class AppHelper extends Helper{
function link($params, $go, $here){ ... code ...}
}
来源:https://stackoverflow.com/questions/5613899/cakephp-override-htmlhelperlink