开发者

Big switch in the view

I'm new to MVC and php framework, so please excuse me for this simple question...

I like to have my views without big chunk of php code but I have a case where I don't really know how to do it properly.

Basically some object has 20+ different states and the state is given by the model. Now I have a :

switch($object->getState())
{
  case 0:
    $sText = '...'; 
  break;
  case 1:
    $sText = '... on the'.$object->getDate(); 
  break;
  ...
  case 20:
    $sText = '...'; 
  break;
}
?>
&l开发者_Python百科t;img src="<?echo $object->getState()?>.png" alt = "<?echo $sText;?>" 
title = "<?echo $sText;?>" /> 

How can I do that without the 40+ lines of php in the view ? I don't want to have to repeat the <img> tag 20 times. For me the text should belongs to the view, not the model.

Maybe a view helper that will assign the text to the state ?


A view helper isn't going to make your code any less ambiguous or better MVC. The text for the view might not belong to the Model, but the logic for determining the text definitely doesn't belong to the view. There's nothing wrong with writing a method like $model->getViewTextForState($object->getState()) - that's basically the same approach as you'd use for string localization for numerous languages.

Think of it this way - the alt text for the view really does belong to the model because the model is responsible for marshalling ALL of the data. If some text in the view is variable, then it is literally model data, just like the image name you're producing from the $object->getState() method. The image name and the alt text for it are data and should be provided to the view from the model with a single line access method


The switch could be in your action, and you could use translation strings like this

$this->sText = 'object_state_' . $object->getState()

then in your view, translating $sText would do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜