Need some advice for templating with PHP/HTML - php

I read this post and I really like this solution to templating but I am unsure of one thing. With this system wouldn't the business logic and presentation logic be in two different php files? This is all well and good as it separates them but what if there is only presentation logic as there are on some pages or what if there is a very low amount of business logic?
It seems weird that the default page the users page to will sometimes be only presentational logic and sometimes only business logic. It seems like there are two obvious solutions to this:
1) Have all default pages have business logic (even if there is none) that link to the presentational logic on a different page. The problem with this is that there are then a lot of "unnecessary" pages. The good is that it is consistent.
2) If there is no business logic for a page then just only include the presentational logic. The problem with this is that it is inconsistent when looking at filenames as to what php page includes the business and presentational logic.
Also, and this may be a little off-topic, but is there any way to template this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Website</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="styles.css" rel="stylesheet" type="text/css"/>
<link href="favicon.png" rel="shortcut icon" />
</head>
<body>
</body>
</html>
Considering I have this on every page I was wondering if there was a way to template this so the code could all be in one file and recalled.

Your templates should contain strictly presentational logic.
This means that you can include:
Loops (to print lists etc)
Conditionals (e.g. only print an element if some value is non-null)
Formatting functions (strip spaces, round numbers, etc)
A small number of template-composition helper function calls (e.g. "please include this other sub-template here")
but nothing else -- and especially not business logic! (if I forgot something important, please mention it in a comment)
Also, your templates ("views") should never be used as the target URLs that you application uses. You should have the URLs point to (possibly one of many) "controller" scripts, which then invoke the necessary business logic and pass the results to your template for display by including the template. You will find this easy to grasp if you are familiar with Model-View-Controller; if you are not, familiarize yourself first.
Finally, here's one way you could template the markup you gave:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $title;?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php foreach ($stylesheets as $stylesheet) : ?>
<link href="<?php echo $stylesheet;?>" rel="stylesheet" type="text/css"/>
<?php endforeach; ?>
<link href="favicon.png" rel="shortcut icon" />
</head>
<body>
</body>
</html>

Related

php with html question about lines and returns

I want the php/html to be like this code
<link rel="stylesheet" type="text/css" media="all" href="
<?php if
But if you write it this way there is a carriage return so it puts a return in the html and that is not the best.
You can write it this way with no carriage return. But the php does not look as organized.
<link rel="stylesheet" type="text/css" media="all" href="<?php
if
Is there a more proper way, a better way?
Avoid nesting if inside html tag, especially if you have block of if conditions, since it does not look neat and it'll be harder to debug the code. I'd prefer to keep them separated.
<?php
if (condition1)$style = 'css/style1.css';
else if (condition2)$style = 'css/style2.css';
else $style = 'css/default.css';
?>
<head>
<link rel="stylesheet" href="<?php echo $style;?>" >
</head>
This sort of formatting conundrum is frequently a pain point w/ dynamic HTML generation. This can be significantly lessened by using a templating system like Twig, but shy of that, I'd recommend migrating to a more view-like design by generating the dynamic block elsewhere, and then just passing the value to your echo statement. Ideally, the value would be calculated in a model and then passed to a view via a controller, but if you've got a more monolithic design, you can sort of fake it by putting your logic outside the HTML block:
<?php
// a bunch of code to calculate what should be in $foo
?>
<link rel="stylesheet" type="text/css" media="all" href="<?= $foo ?>">

Converting my single page site to html5

At the moment I have a single page site (html/php) I created for someone about 2 years ago. I'm about to add an admin panel and plan on starting with html5 for it. I'm curious what I will need to do to my single page besides switching the <!doctype> to just html.
Here's a bit of my single page index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="descriptions" content="meta desc">
<meta name="keywords" content="meta, keywords">
<!--imports the main css file-->
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body></body>
</html>
I know first I'll change my doctype to <!doctype html> but don't I also have to remove extra properties of my link and script tags? Namely the type property?
Currently this is a simple 1 page site, so I thought it would be a great place to start.
Thanks!
That should be it. Do that and then put the URL in http://validator.w3.org/ to see what html 5 errors you have.
Also since it will not be XML I think you'll want to remove the forward slashes from the end of the meta and link tags. See Useless Code's comment below regarding the type attributes.
The validator will tell you each problem until your html 5 is valid.
The HTML 5 code would look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="meta desc">
<meta name="keywords" content="meta, keywords">
<title>Title</title>
<!--imports the main css file-->
<link rel="stylesheet" href="css/style.css" media="screen">
<script src="js/jquery.form.js"></script>
</head>
<body></body>
</html>
Some explanations:
xmlns is no longer needed. Elements in HTML5 don't need to be explicitly delcared.
I'd go with charset meta before title. Otherwise, IE users might be left in the open in front of an XSS attack. (https://code.google.com/p/doctype-mirror/wiki/ArticleUtf7)
on the second meta, the name attribute should be description, not descriptions.
there's no need for forward in html (at the end of meta, links). those were mandatory in xhtml.
when referencing link and scripts, you can choose not to mention the type attribute. It is considered redundant as the defaults will kick in (for link you would probably use css, and for script js)
If you want to find out more about HTML 5 - here are some good places to start (stuff that you can read and enjoy while at it, compared to the actual standard):
http://diveintohtml5.info/ - free e-book by Mark Pilgrim

Is it good practice to add a php include of the head section in my pages?

I am creating my portfolio site and I am wanting to include the head section as a php include on my page. Reason being is because the site will have a fair few pages and I will want to make changes later on to things later on like tidying up the css files.
For example;
<head>
<?php include('head.php'); ?>
</head>
as opposed to all this below being shown on each and every page:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/1140.css">
<link rel="stylesheet" href="css/ie.css">
<script src="js/vendor/modernizr-2.6.1.min.js"></script>
</head>
I just didn't know if this was good practice to do, as with this being my portfolio site, I need the code to be correct from the start also as they will probably look into the standard of it also.
What are your opinions and advice people? Thanks.
Yep, it's quite standard. But instead of writing:
<head>
<?php include('head.php'); ?>
</head>
you should put the tags inside head.php. I say it's better because what's inside head.php has no sense without the head tags, so they are kinda linked together. It's good practice to join things so linked into a single file without having to repeat open and close head tags for each page.
Actually, it's even good practice (and commonly used) to have header.php, body.php and footer.php files that has respectively:
header.php
<html>
<head>
...
</head>
<body>
body.php
...
footer.php
</body>
</html>
I'm doing that in my application but I've found that it's not a good idea, because you have many of your stylesheets, javascripts, etc in a php file including the head section and you'll have problems with including it in php files in nested folders. this problem is because of relative paths.
If you can use absolute paths then it's ok otherwise it's not a good idea ...
PHP Includes are used like this all the time. Any time that you have content that will be the exact same on every page, it is very helpful to use an include
This is an old topic but I use
<?php include_once("phpinclude/head.txt"); ?>
phpinclude is it's own folder and I keep the footer, header, and common place info in that folder. .js, and .css has it's own as well.
Edit: I use require now. I would rather have a code fail and die rather than give some random string. They are the same except one dies and the other will print out an error or random code. This is for people learning PHP, not old heads.

Is it a good practice to store head tag information in a separate file and later include it?

<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<link rel="stylesheet" type="text/css" href="css/homepage.css"/>
<link rel="stylesheet" type="text/css" href="css/header.css"/>
<link rel="stylesheet" type="text/css" href="css/footer.css"/>
<link rel="stylesheet" type="text/css" href="css/navmenu.css"/>
<!-- more css here -->
<script type="text/javascript" src="js/jQuery.js"></script>
<script type="text/javascript" src="js/navmenu.js"></script>
<!-- more js here -->
</head>
i have all of that external css and javascripts inside the <head></head> tag in all of my pages and all of that are important in all pages.. is it appropriate to put all of that in a separate file and just include that using php? so if i want to make some changes on those externals it would be easy for me, because it will affect all my pages.. i just want to know if it is a good practice.. thanks in advance
Yes, it is. But why stop there? Ideally you should have all of your repetitive markup in a single file.
There are numerous approaches to sharing common markup in PHP, but the simplest way is to have a global "Top.php" and "Bottom.php" files, like so:
In Top.php:
<html>
<head>
<title><?php echo $pagetitle; ?></title>
<!-- your <meta /> elements go here -->
</head>
<body>
<!-- common page elements go here -->
In Bottom.php:
</body>
</html> <!-- This ensures all of the common markup is closed -->
Then for each page, do this:
<?php $pageTitle = "This page's title";
require("Top.php"); ?>
<!-- put your per-page markup and PHP code here -->
<?php require("Bottom.php"); ?>
Simples.
Now how I use require() instead of include(). The require function is more strict and basically ensures that the included files exist. I think it's better for an application to visibly break than to fail silently.
Save your snippets to separate files and then include() them.
And yes, it is a good practice, but much better is to use some decent templating system.
Look at Latte templating system from Nette Framework
Sure It is good practice. Put this in a separate PHP script ie head.php then include in all other pages using
<?php include('head.php'); ?>
To answer your question straight forwardly.
YES! It is a good practice.
A good programmer will not re-code everything at every page (one of the necessity lead to the invention of CLASS). So. Carry on! :)
Yes, it's appropriate to pull common data like that into separate files. The question really is, now that it's in a separate file, what do you do with it?
You have at least four options.
server-side (host-based) include files
php include statement
php require or require_once statement
make
Server-side includes are generally believed to hurt performance, especially on low-cost (oversold?) shared web hosting servers. There are other issues.
The include and the require statements in php differ mainly in how they respond to missing files. The include statement produces a warning; require produces a fatal error.
The make utility is less commonly used, but it's very useful. Using make, you can include any file within another file, producing output that has static content when it makes sense to have static content, and dynamic content when it makes sense to have dynamic content.
For information like you're talking about, you could use make to produce files in which the stylesheets and javascript references are static (so there's no performance hit), with all the maintainability of a single source file. A properly built makefile guarantees that any change to the stylesheet/javascript file will be incorporated in the next build.
Other text utilities can do some of the same things, especially if you're only talking about file inclusion. (m4, for example.)

"echo" in functions or "echo" all page?

Is this a good method to save to all index in a variable and then echo this? for example
<?php
$txt='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<h2>'.heaf_func().'</h2>
</div>
<div class="content">content</div>
<div class="footer">footer</div>
</div>
</body>
</html>';
echo $txt;
?>
I'd personally change your example to be like this;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<h2><?php echo heaf_func(); ?></h2>
</div>
<div class="content">content</div>
<div class="footer">footer</div>
</div>
</body>
</html>
Generally, no. If you need to do output buffering, just use the output buffering API. Even if you need to retrieve your output to do post-processing on it, you can do that using ob_get_contents. It won't be a big deal on most pages, but on large pages or under heavy server load you should use the output buffering support because it's better optimized for what you're trying to accomplish.
Generally, when looking at a method such as what you're contemplating, ask yourself "what does this gain me?" Your example above is clearly trivial, but unless you're planning on post-processing your results, what does it gain you?
EDIT:
I've used both the PHP-in-XML and XML-in-PHP approaches in various projects. My experience is that on a project of any significant size the PHP-in-XML (or HTML, but I try to always generate XML or XHTML) eventually turns into nasty spaghetti code that becomes a pain to maintain, whereas the XML-in-PHP approach eventually balloons into a mess of string-manipulation code that you also don't want to maintain.
Generally, I'd recommend going with an MVC (MVVM, MVP, etc. - up to you) framework for every web app, regardless of language. If applied correctly, the additionally framework complexity is more than compensated by the modularity and ease of maintenance and extensibility that you gain. If you don't feel the need or desire to target a framework (though, again, I STRONGLY recommend it), I typically follow these rules:
Whenever possible, limit PHP-in-XML to simple inclusion of values. E.g., <h1><?php echo $title; ?></h1> Try to avoid including logic in your spaghetti code (other than, perhaps, repetition, though I typically abstract that away, too).
Whenever possible, create XML documents using the XML API's instead of writing raw values to the output. XML has the advantage of being easily transformable, which in my experience is well worth the extra initial investment, at least in production apps.
Send the client an XML document representing your data with an xml-stylesheet processing instruction indicating the location of a stylesheet to apply for rendering and let the client do its own rendering. Failing that, put your data-to-presentation transformation logic in a stylesheet (XSLT, not CSS) and do the transformation server-side. I really enjoy the separation between data and presentation it allows me.
The question is why you want to do this. Just putting it in a variable and then echoing it isn't worth it but if you need to work on the string further (string replacement, etc.) it is useful.
If you're going to be doing massive multi-line text-into-variable assignments like that, consider using the HEREDOC syntax, which has the advantage of not forcing to you escape quotes, which makes the text blob far easier to read and cut/paste into other things without needing tweaks.
As for choosing if you should do PHP-in-HTML or HTML-in-PHP, it all comes down to which one would be more readable. If you have 500 lines of HTML, and only a small bit of PHP to insert, then go for PHP-in-HTML, and vice-versa. For a near even-balance, it'd come to whatever your preference is.

Categories