Using a switch statement isn't probably the best practice here. Everytime you need a new type you would have to add a new case. It would be better to store the corresponding labels along with the data in your class in my opinion. But let's tackle the problem.
One thing you can do is to implement a Decorator for your prop
class that adds a functionality to get the corresponding Label.
class PrintLabelPropDecorator {
protected $prop;
public function __construct(Prop $prop)
{
$this->prop = $prop;
}
public function printLabels()
{
switch($this->prop->type)
{
case 'foo':
echo 'Label1: ' . $this->prop->data1;
echo 'Label2: ' . $this->prop->data2;
break;
//[...]
}
}
}
The first thing we do is to inject the class we want to decorate into the constructor.
Then we write the actual decoration method printLabels()
. That does the actual check and prints the label information.
Now we only need to decorate the actual class. For simplification reasons I do this in a pseudo-controller method. You should outsource it by your demands.
<?php
public function myControllerMethod()
{
//$props = whatever you need to do to get the prop objects
$printLabelPropDecorators = [];
// That should usually better not be handled by the controller
foreach($props AS $prop)
{
$printLabelPropDecorators[] = new PrintLabelPropDecorator($prop);
}
$this->view->create('myfancyview', compact('printLabelPropDecorators'));
}
We create an array that will hold our decorated objects and then iterate trough the base objects and create our decorator objects. Then we simply pass the array with our decorators to the view. (The decoration process is not quite elegant, you could for example write some kind of Collection for this).
Now the only thing left to do is the view. It should be self explanatory:
<?php foreach($printLabelPropDecorators AS $prop): ?>
<?php $prop->printLabels(); ?>
<?php endforeach ?>
That could be one approach to do it. The actual logic that decides which labels to print does now live in the Decorator and you are not cluttering your view.