Question

I would like to include a stylesheet and other documents only if they are present in the presentation layer. How is it recommended to handle it? I show the two alternatives I see now in their respective layers:

Presentation:

<?php
$internalpath = "/internal/path/style.css";
if (!file_exists($internalpath))
  throw new Exception("Couldn't find style.css in " . $internalpath);
else {
?>
<link href="/external/path/style.css" rel="stylesheet" type="text/css">
<?php } ?>

Problem: it is bloating the view with business logic

Business logic:

<?php
$internalpath = "/internal/path/style.css";
if (!file_exists($internalpath))
  throw new Exception("Couldn't find style.css in " . $internalpath);
else
  $style = '<link href="/external/path/style.css" rel="stylesheet" type="text/css">';

// ...
?>

Problem: it is bloating the business logic with part of the view.

How can I separate these concerns properly? Is there any other simple alternative I'm not seeing?

Was it helpful?

Solution

Both solutions are invalid, exactly for the reasons you give - you're not separating them properly. Correct would be:

Business Logic

$customStylesheets = [];
$internalpath = "/internal/path/style.css";
if (!file_exists($internalpath))
  throw new Exception("Couldn't find style.css in " . $internalpath);
$customStylesheets[] = RewriteToExternal($internalPath);

Presentation

<?php foreach($customStylesheets as $stylesheet) : ?>
    <link href="<?=$stylesheet ?>" rel="stylesheet" type="text/css">
<?php endforeach; ?>

This way the business logic worries about what needs to happen, and the presentation about how to render it.

As for the general question: no, exceptions should never be thrown during rendering. Once the business logic has deemed a request acceptable, it should render completely and correctly. The presentation layer is not about decisions, just about output. If something fails 'exceptionally' at that point you screwed up the error checks in the BL layer.

To make these questions more obvious, don't use PHP as a template engine but grab a beautiful thing like Twig which forces you to keep your templates purely presentational. PHP as a template engine is just too big an invitation for some to separate things correctly.

OTHER TIPS

Why not throw Exceptions in the view layer? As long as you have a way to properly handle these exceptions in the application and ultimately display an appropriate 'Oops' type page ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top