1

Suppose I pass an array, which can contain instances of two different classes, to View template, which contain table markup. Each item will be presented as table row, so I need to check it's class name in order to include appropriate row partial. So far I can see only two ways to achieve this goal:

  • compare class name using get_class function
  • add isFoo() method to both classes, which will return true if object's class is Foo

I don't like the second option, because it's harder to maintain in situations where I have more than two classes, but I wonder if first option is commonly used and get_class function is appropriate to be placed in View templates.

Example in laravel's blade template:

/* catalog.cycle_rows.blade.php */
@foreach($cycles as $cycle)
@include('catalog.cycle_row')
@if( $cycle->subcycles )
    @include('catalog.cycle_rows', ['cycles' => $cycle->subcycles])
@else
    @foreach($cycle->cycleItems as $cycleItem) 
        @if($cycleItem->isBlock()) // here's the check
            @include('catalog.block_row', ['cycle' => $cycleItem])
        @else
            @include('catalog.cycle_item_row')
        @endif
    @endforeach
@endif
@endforeach
tereško
  • 56,151
  • 24
  • 92
  • 147
ivan.c
  • 273
  • 3
  • 13
  • I'm not sure checking the class name is the best way to go about this. I don't really know how your application works, but I'd probably use an instance variable or method like your option 2. – grimmdude Feb 23 '15 at 20:07

2 Answers2

0

I'd do neither of the suggested options and use instanceof:

@if($cycleItem instanceof Block)
    @include('catalog.block_row', ['cycle' => $cycleItem])
@else
    @include('catalog.cycle_item_row')
@endif
lukasgeiter
  • 124,981
  • 24
  • 288
  • 251
  • I'm not sure that either `instanceof` or `get_class()` should be put in templates. I found the answers there sharing the same opinion: http://stackoverflow.com/questions/10113442/twig-instanceof-for-inheritance-objects – ivan.c Feb 24 '15 at 09:47
  • Hmm yes this should probably be avoided. But if you can't / or don't want to avoid it I'd use `instanceof` instead of `get_class()`... – lukasgeiter Feb 24 '15 at 09:52
0

I would use a view presenter. This will allow you to wrap "model-to-view" logic in a separate layer specifically for this functionality.

Aken Roberts
  • 11,722
  • 3
  • 31
  • 39
  • As far as I know, view presenters are used for decorating an attribute or imitating of having one. I'm not sure it solving the case, but thanks anyway. – ivan.c Feb 24 '15 at 09:54
  • A view presenter is designed to add view-specific logic on a layer in between the model and the view. You don't want complicated PHP conditionals in your template, nor do you want them in your model because it isn't part of your domain code. That leaves the controller, which you want to keep minimal anyway. – Aken Roberts Feb 24 '15 at 20:13