I have a modifier procedure to show the "date" of an event.
if($event['Event']['is_multi_day']){
if( date('n',strtotime($event['Event']['start_day']) ) == date('n',strtotime($event['Event']['end_day'])) )
$date = date('j',strtotime($event['Event']['start_day'])).' - '.
date('j',strtotime($event['Event']['end_day'])).' '.
date('M',strtotime($event['Event']['end_day']));
else
$date = date('j',strtotime($event['Event']['start_day'])).' '.
date('M',strtotime($event['Event']['start_day'])).' - '.
date('j',strtotime($event['Event']['end_day'])).' '.
date('M',strtotime($event['Event']['end_da开发者_如何学Goy']));
}else{
$date = date('j M', strtotime($event['Event']['start_day']));
}
I have to include that code block in every page I display an event. How do I define a function for this, which can be called from views I want?
Looks to me like you're going to be using this in a loop that displays a number of events and your code will be far from optimal in that situation.
I think you can reduce this line:
if( date('n',strtotime($event['Event']['start_day']) ) == date('n',strtotime($event['Event']['end_day'])) )
)
to:
if($event['Event']['start_day']==$event['Event']['end_day'])
(or something similar that compares the stored value without formatting. Formatting is for display purposes, not algorithmic comparison)
and this:
date('j',strtotime($event['Event']['end_day'])).' '.date('M',strtotime($event['Event']['end_day']));
to:
date('j M',strtotime($event['Event']['end_day']));
...and similar edits elsewhere. If this is in a loop, you need to reduce the number of unnecessary function calls and avoid concatenation of strings.
Personally, as this is a display function, I'd keep it on the view side of things (as opposed to the controller) and I'd probably do it as an element with passed parameters - see http://book.cakephp.org/view/560/Passing-Variables-into-an-Element
I would create a helper for this. For me it's more sensible rather than a component. If you using this data only to display it I believe that Helper is the proper solution. How to build custom helper
If it's raw data that you're manipulating (as shown) and you just want to return a value for display, I'd create a component and do it at the controller level. If you want to include presentation markup and/or logic, then an element is probably what you're looking for.
精彩评论