HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Is this violating the DRY principle?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisviolatingtheprincipledry

Problem

I feel that I am repeating myself a lot with this HTML/PHP code. Am I right, and is there a maintainable way of reducing the amount of repetition in the code?

mydomain/index.php:


Home - This Website

Home
Introduction.
Some content.
More content.


mydomain/somedir/index.php:


Some Page - This Website

Some Page
Some content about this page.

Solution

Consider using existing template systems to help you that support inheritance. Template inheritance isn't a strict requirement, but is a powerful feature that makes maintaining templates a lot easier. Twig is easy to use, and feature-rich.

If you want to go it your own way, you could simply implement the use of layout files:

layout_default.php


" />
" />


example page.php


 main body html
<?php
$title = "x"; 
$description = "x"; 
$keywords = "x"; 
$contents = ob_get_clean();
require 'layout_default.php'


This is a very crude implementation, simply enough to illustrate the principle.

Code Snippets

<!DOCTYPE HTML>
<?php $root="/mywebdir"; ?>
<html>
<head>
<?php include("$root/inc/meta.php"); ?>
<meta name="description" content="<?php echo $description ?>" />
<meta name="keywords" content="<?php echo keywords?>" />
<title><?php echo $title ?></title>
</head>
<body>
<div id="main">
<?php include("$root/inc/header.php"); ?>
<?php include("$root/inc/nav.php"); ?>
<div><?php echo $contents ?></div>
<?php include("$root/inc/footer.php"); ?>
</div>
</body>
</html>
<?php ob_start() ?>
<p> main body html</p>
<?php
$title = "x"; 
$description = "x"; 
$keywords = "x"; 
$contents = ob_get_clean();
require 'layout_default.php'

Context

StackExchange Code Review Q#11819, answer score: 4

Revisions (0)

No revisions yet.