How to template in PHP... the right way? - php

I'm starting to understand the importance of templating in PHP. I'm using PHP itself as a template engine to avoid learning any new language. I'm still not clear on one thing tho, although I have an idea about it. I would like to know what the experts do.
Should I create a full page template, with all tables, forms and everything else (including header and footer), or should I put all of my tables, forms, etc in their own file and then add them to the template as needed.
Here's a small example to clear things up...
Should I
a) create one page with all the tables, forms, and other elements in it and use that as a final product
// Set all the information
$template->title = $username;
$template->user_info = get_user($user_id);
$template->articles = get_articles($user_id);
$template->ads = random_ad($user_info);
// Load the template with everything already in it
$template->load('user_page.tpl')
$template->display();
OR
b) create every table, form, related block element in its own file and then use those to create a final product
// set the title and load the header template
$header['title'] = $username;
$template->load('header.tpl', $header);
// get the user info as an array and load into user profile template
$user_info = get_user($user_id);
$template->load('user_profile.tpl');
// load the new article form
$template->load('new_article_form.tpl');
// get the articles as an array of info and load into user articles template
$articles = get_articles($user_id);
$template->load('user_articles.tpl', $articles);
// get a random ad based on user info
$ads = random_ad($user_info);
$template->load('advertisements.tpl');
// load the footer template and display final page
$template->load('footer.php');
$template->display();
Where every file loaded contains a small portion of what needs to be displayed on the final page.
Because of the Dont Repeat Yourself technique, I would think B, but i would like to know which and why

I would personally say the first approach is best, because it keeps all documents and document fragments semantically complete.
The second approach means that you'll have a <div> in your header.tpl that is closed by a </div> in your footer.tpl (except likely there will be a few tags that applies to). This means if you change your layout, by adding a wrapper div (for example) somewhere, you have to remember to also close it in another file (or, depending on your layout, two or three different files).
It's worse with several different embedded files. Think of how hard it is to debug a site, when one file - that gets included conditionally - has an extra </div>. You get a vague bug report "sometimes the page looks completely messed up, doesn't matter what browser I use" that is very very hard to track down. It's MUCH worse if you're using table-based layouts..
Using the first approach, you can still use the DRY principle. You load the template into a variable. eg:
$userVars['name'] = $currentUser->name;
$templateVars['userinfo'] = $template->load('userinfo.php', $userVars);
...
$template->display('template.tpl', $templateVars);
You can continually nest documents that way. There are many benefits:
Each file is semantically complete HTML - all tags that are opened, are also closed in the same document. It's easy to edit one part of the layout without breaking (possibly unknowningly) anything else.
It's each to cache the output of certain templates, and re-use them
It's easy to apply AJAX to the site. For example, you have a stats.tpl template rendering inside a <div id="stats"> on the first page load. You also have a view that just renders the stats.tpl template by itself, and then use jquery to do $('#stats').load('/ajaxstats.php'), which refreshes that div but without repeating code at all.

Template inheritance for structures common to every template (e.g. layout; header/footer), and template embedding (i.e. including) for reusable bits (e.g. forms).
With approach A and without inheritance, you'd be either including common layout elements (which is IMHO ugly), or duplicating entire layout in every template (which is even worse). And plain approach B would create massive amounts of tiny template bits for everything, which may reduce maintainability.
And for that, I really recommend using real, dedicated templating engine instead of plain PHP. They make life easier (inheritance is one thing; another - variable auto-escaping).

template inheritance would probably make the cleanest code. you can do this now in straight php using PHP Template Inheritance

There is no good or bad solution. There are techniques and guidelines but in time you will learn what approach is better than others.
Just by looking at it i would say that the second approach allows you to be more flexible and breaks down the page into smaller parts. Smaller might some times mean more manageable.
Also the second solution also allows more than 1 persons working on the page since they will only need to work/change parts of the page and not the whole page.
regards,

As gregmac suggested, the first solution is probably preferable. Having said that, I would also suggest to have a look at the various PHP frameworks available, most of which implement templates using various techniques.
Have a look at this list for a start. You may also want to take a look at some stand-alone template engines, such as Smarty, in order to get some ideas or to avoid implementing your own engine.

Related

How should I keep webpages consistent [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm fairly new to web-centric design and programming.
I've got a HTML + CSS with PHP page I'm quite happy with. It's got a header, a main content area, and a sidebar.
Now I'm working on my second page. The second page should have the same look as the first page. I'll reuse the CSS, but there seems to be a lot of repetition between the first and second pages (the content in the header, and the sidebar, for example, is almost identical).
Is it normal to repeat things over multiple pages? If, later, I want to change something, I'm going to have to change it in (potentially) numerous places; that seems rather silly, so I presume I'm missing something.
I thought perhaps I'd use the "small parts" from my CSS in a "larger" wrapper, encompassing the entire Header, perhaps, and then include that in both pages; I'm not sure if that's the right direction I should be heading (or how I'd do it).
I also thought perhaps I could use PHP to dynamically generate the page each time, wrap the generation in a class, and then end up with something like myClass->generateHeader(). I'm using PHP to generate some of the page anyway, so the conceptional leap isn't too great; on the other hand, I imagine that generating the page each request is worse in terms of performance, and (from my brief searching) seems to involve several hundred lines of PHP to generate a rather short stretch of HTML, (assuming it's anything more complicated than a bunch of echo statements containing the HTML I'd have written anyway.
Searching for "creating HTML templates" is rather fruitless, but I'm not sure what kind of keywords I'd be using to ask how this is normally handled.
How do you adhere to DRY and avoid repeating yourself over several related pages in a website?
You can use the php include method: http://php.net/manual/en/function.include.php in order to not have to repeat parts of your page that are always needed. For example, the header and footer, navigation, etc..
To answer your other question, using a class to store html sections is another way to go and can prove to be useful. It also won't add a lot of extra processing time unless your class needs to do a lot of calculations upon initialization.
A common practice is to seperate out a header and footer file and include them. A good book on this would be Larry Ullman's php and mysql for dynamic web pages.
But for a quick overview go to: http://www.davidjrush.com/blog/2009/08/php-header-and-footer-templates/
If you fear that some things do repeat across multiple resources, keep them out.
Add them in post-processing instead.
You do this best on the server level. You can also add caching if needed at that level, so your page only get's generated once and no-more again (or until the cache expires).
I agree with Matt K, that is probably more programmers stack exchange related but I'll provide some tips anyway.
I think the normal thing is to create some kind of header/footer files. For example, your header file would include everything you want on every page, i.e. logo, menu, css includes etc. And the footer is useful for: closing wrapper divs, google adsense code etc.
Once these files have been created, for each page you just do:
<?php include("header.php"); ?>
BODY OF PAGE
<?php include("footer.php"); ?>
:)
If any of the components are static components (e.g. the sidebar), then you can put the static HTML in a file and simply include it in the relevant place. (OO alternative: have a View object pull in the static HTML for you.)
If you need some custom logic in these components, then an include could still work, but since you discuss a class-based alternative I'd suggest building an MVC architecture into your application.
An MVC framework would probably consider the header/sidebar/footer etc. as partial views (smaller components in the main view), or part of your overall layout (your header/sidebar/footer wrap around your main content body).
The layout option makes a lot of sense as it decouples the view for the main content from your overall idea of how the page components stick together. It also means it's really easy to modify the layout (for instance, put the sidebar on the right instead of the left by changing one layout file).

Bespoke PHP Templating Engine

As a small part of a university project I'm working on (custom MVC based project management system), I need to develop a template engine. I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
Anyway, I've managed to code something simple so far, I have a class, create an instance of it, add some data to the instance, then pass in a template file. The file has a series of tags like {this} when then get replaced with the data. Simple.
The issue I'm having is when it comes to looping things - i.e. a table of users or a list of categories. At the moment I have a template file for the page (users.html) which contains the opening and closing tags, with a template tag between them called {users}. I then have another template file (users-detail.html) which displays a table row with the user info in. I'm creating a new instance of the users-detail.html template, adding the data, parsing it, then placing the output (string of HTML) into an array. I then loop this array, attach all the strings together, then assign this to the {users} tag in the users.html template file.
As you can probably tell from that explanation it is a bit of a bodge, and there are probably better methods out there for doing what I'm trying to achieve. Ideally I want to avoid using PHP in the template files if possible, and I often need to have multiple loops within one template file.
If anyone has any tips / advice on how I can achieve this, or any tutorials I could follow to get some inspiration that would be much appreciated.
Thanks in advance.
I've seen that approach before (including another template for the insides of loops). I used to work on an old version of vbulletin which does (or did) this. It makes things annoyingly complicated because you can't just add a loop to a template - without setting up a whole new template for each layer of looping.
I'd advise you instead to go along the route of Smarty.
Classically, this statement:
I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
... indicates you really should just be using Smarty. In the real world that would be a poor justification for re-implementing something yourself. But I am like you, and I understand that you want to implement something yourself (because you want to learn, you find it fun, you are a perfectionist, etc). As long as you do it on your own time and it's a personal project, go for it.
It would be worth studying Smarty to see how it works (not just the syntax but how it compiles templates, stores the compiled version etc). Are you comfortable writing a tokeniser/parser in PHP which can compile your template language and output PHP? If you are advanced enough to do it, do it. At the very simplest, you read in a tag like {foreach from=$something} and somehow translate it to <?php foreach ($something as $thing) { ?>. You check token types, etc to make sure the template tag is valid, and so on.

What architecture should I use for writing my first dynamic website in PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I just want to build my first dynamic Website. I want to use PHP, MYSQL, AJAX, HTML, CSS
I have some beginner Questions:
Should the Header and Navigation Bar excluded in a header.php and print out with echo?
Should the design tags in the echo in php (like: <a>1 Test test</a>) or only return the the data
Is there a good example for making dynamic websites?
My main problem is that i don't know how to make a clear structure. Where to make the right design (print out in the php ?)
If it is really your first website, I'd actually recommend using nothing in terms of frameworks. This buys you some time to get comfortable with HTML/CSS, SQL and PHP, without overloading you with higher-level principles such as MVC (model/view/controller) and others. I'm mostly concerned that starting with a framework right away makes the learning curve to steep, and skips over things such as getting comfortable with the programming language you'll be using.
You'll eventually make a mess with way, but this will only make you appreciate the frameworks more; you can then make the transition to using a framework such as CodeIgniter, Symfony or CakePHP (or others, because there's a whole bunch more).
Other frameworks that I really like working with are Play! for Java, and Rails for Ruby. Since you stated you're a beginner, you might consider these as well.
Well, to answer all your questions at once.
The only technology you need is template.
Template is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.
Create a main site template contains both header and navigation bar and footer everything else excluding actual page content.
Then create separate pages ("sections" of your site: news.php, links.php, etc.)
But make every page of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a main template.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Yes, I do recommend you include header and navbar scripts from another file.. where you can maintain them independently. I think that is pretty important.
I recommend you echo/print html from php, rather than insert php into html (easier when doing things like parsing $_GET/$_POST etc)
I recommend that you create a template, and another script which has functions that print (or echo) the html tags, header, footer, title bar, navbar etc. Just include the script with the functions and all your pages can have the following structure:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION,etc
if needed */
print_html_pre_content();
print '<p>Hello, world! or other content.</p>';
print_html_post_content();
?>
I have found this to be pretty clean, and it is easy to add functionality when you get to messing around with $_GET, $_POST and $_SESSION, etc.
I'd suggest to use some template system (Smarty would be good).
It does not really matter where do you put your header and navigation bar at first glance. When do you need to exclude Navigation bar and store it separately? When you want to have ability to include different nav. bars in different parts of your website.
For example I have a website with several subdomains: about.website.dev, special.website.dev and, let's say, terms.website.dev
At about.website.dev my navigation bar's entries will be: "Who I am", "What do I do", "How cool am I"; at special.website.dev: "Goods", "Solutions", "Tips" , etc.
Your navigation bar's template is the same: just a loop though all entries, but content differs. In this case you separate navigation bar from header. If you don't use templates, you just create three files (in this case): about.nav.php, special.nav.php and terms.nav.php and then you just include appropriate navigation bar.
If your nav. bar is all the same everywhere on your website, you can store it in header.php. Once you need to separate, it will not be difficult, but still I'd suggest to use templates though just to get used to "proper website development".
Take a look at different templating systems like Smarty or Savant. I, personally, like Django's (python) templating system most. And get used to separate your view and business logic.
IMHO, you would be better off having a look at a php-based web application framework. such as the list at http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
Even though it may be a little more to learn upfront (the framework as well as php), they all have solid enough structures to develop dynamic websites with. Find one that is light enough and has good tutorials and you'll find yourself learning the php language along the way. I believe this will be easier than just using raw php at the beginning stage.
When you know more you can then make a judgement call on which frameworks you prefer and suit your needs or coding style or even revert back to raw php.
If you want a good book on the subject, try
MySQL/PHP Database Applications by Brad Bulger, Jay Greenspan and David Wall
What you are asking is pretty much a matter of taste. The more complex your application will be, the more work should go into an elaborate and maintainable structure.
My opinion is: Learn the basics first and then look at frameworks. It makes it a lot easier if you understand what happens under the hood.
Try Agile Toolkit, probably the easiest PHP UI framework to get started with designed for web software.
You'll step over many problems. http://agiletoolkit.org
Depending of the choice of framework/plain PHP, you should do it in accordance with their practices. For instance in Agile Toolkit you use templates, so you put your header and footer into templates/jui/shared.html file. It's explained in the first screencast.
If you reinvent the wheel and go ahead with plain PHP, then you should do better do include 'header.php'; . Good framework lets you NOT learn about inner workings of web software. Bad framework needs you to know everything anyway.
There's a lot of good answers here already - but just to add....
Do split functionality into separate include files - and use a consistent way of locating these files.
Do find a good PHP coding style and stick to it. e.g. horde, PEAR
Don't have code or HTML executed inline in include files - it should only do something when you specifically invoke it from your controlling script.
If you are including files which generate HTML, make sure they provide functionality for closing any tags they open. i.e. not just a 'header.php'
Since CSS and Javascript files should not be directly declared outside the HEAD of the HTML document do look at ways by which invoked functionality can add these into an existing HTML document - one obvious solution is to use a templating system combined with output buffering but you can also inject additional JS and CSS files into the HEAD section later in the document by using javascript.
Use MVC - http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
See Yii-framework http://yiiframework.com, it has all you need :)

Building PHP WYSIWYG Editor

I am building a web application in which the user may add a page, edit the layout, drag drop element, resize element, format the text, edit the element attribute etc.
In the page the user may include (retrieve) dynamic data, like maybe data from database, data generated by php code, etc.
I have played around with cakephp and jquery lately and tried to build this app. But I stumbled upon on how to appropriately display the php code. I tried to look into the cakephp core code and find about output buffering and tried to utilize output buffering to parse the php code and use regex to display it but it is more likely to reinvent the wheel if I write the parser my self
What I am asking is:
Ok, to be more simple and specific I just want to ask, how to save and load the page that was created by the user especially if the page contains php code. I just want to know is there any other method than write my own parser or maybe a library to parse a php code?
Ok that's all for now, does anyone have any idea how to implement it? Or maybe any page / website that could be useful to take some reference from? Maybe a sample code from which I can take some reference
Thanks
I'm not sure you'll find any good answer here about that.
Whoa I don't know where to start. I'll start by the number 3. You want widgets. Then that means you have to create widget class or objects that possesses a template or something that makes them drawable "well, kinda". If I were you it would be loaded from javascript and not really from php. Each widget would be in some way individual applications loaded in a div using javascript.
Point 2, You wanted widgets. When you add widgets to your page, you have to save some informations, like Position, Title, dimensions and so on. You may even save creation parameters. For exemple a ListWidget may be started with different ItemProvider. That way you don't have to write 1000 widgets but only one that shows different content. That said you have widgets, dimension and position. Now that lead us to point 1.
Point 1. Once you have your widgets, position and dimensions, you send the data you used to create them associated with the page to the server. That lead us two point 2 again.
Once you have saved a page. You can see it by retrieving all widgets with parameters and so on. That leaves you 2 options.
Generate Javascript that will recreate the saved widgets.
Generate Html will all the widgets.
Option 1 is simpler since option 2 won't bind html to javascript by itself. Solution 2 on the other hand is better since there is only 1 request to the server.
Oh and a last thing, You should set yourself some limits. That kind of thing can get very complicated and unfortunately not that great. See drupal for example. It does lots of cool stuff but as soon as you install lots of module. Drupal transform itself in some sort of memory eating monster. And almost all the time you don't really need that much of dynamic content. Fixed layouts will do work nice almost 99% of the time.
I'm also forced to say that but if you try to create an application that give users as much power as a scientist that could raise a 7 legged cat. I think you're going to play with really obscure forces!

How to get started with PHP themes?

I have a web application developed using PHP. I want my users to select themes for their pages throughout the application.
Where should I start before using PHP themes?
What should I know about Themes in a PHP application?
Edit:
My question about themes is only about changing the color of the layout, not the images.
Suppose My ADMIN user will have white and Orange, but my staff user will have white and green...
How it can be done in PHP with CodeIgniter?
There are lots of directions you can go with this.
1) "CSS ZEN"
This is where the markup remains unchanged, but you totally change the design just by using CSS and images. Demonstrated very well on http://www.csszengarden.com/
2) MVC Stylee
This is where you create a model that represents the page data and then pass it to a view, which contains some inline echo statements. The idea is that you could send the same model to a totally different view so it could look entirely different, HTML and all. Cake PHP is a good start for this: http://cakephp.org/
Example:
<div class="content">
<? echo $Page->Content ?>
</div>
3) Micro-Markup
With this method, you add your own "special tags" to an HTML page. You then read in your plain HTML page and replace the special tags with the information you want to display. This is good if you want your templates to be recognisable to HTML guys that don't know PHP and might break the PHP code in the MVC app.
Example:
<div class="content">
<#Content#>
</div>
Out of all of these, MVC is a very structured way of achieving what you want - however, I listed the other options as they cater for specific scenarios that might be relevant to you.
I have implemented the concept in all three of these, in situations that were appropriate for each.
Regarding The Edit In The Question
I imagine you'll have "something" that represents your user - so it is as easy as:
(In the event of just wanting to override a few settings...)
<link href="style.css" type="text/css" rel="stylesheet">
<?php if ($User->Type === USER_ADMIN) { ?>
<link href="admin.css" type="text/css" rel="stylesheet">
<?php } ?>
You can adjust this example in the following ways:
Use a switch statement if there will be many user types
If the replacement is total, rather than just a few overrides, you may want to completely swap the stylesheet.
You would usually set up template files that contain the HTML and CSS, and build in the PHP generated values at runtime.
The best approach to this is to have the theme reside in a separate directory, containing no code, just template variables like {mainmenu}, {backbutton}, {content} ... you get my drift. Those are then filled by your PHP script, possibly with the help of a template engine like Smarty (No need to re-invent the wheel here).
There is also the approach of having PHP markup directly in the template file(s) like echo $xyz; while this is a perfectly valid practice I use myself often, I recommend using a template engine over using PHP markup in the code if you want a solid, future-proof templating system because:
First, there is less that a designer can break when working on the HTML.
Second, having PHP markup in the code is a temptation to program PHP logic inside the template (loops, conditions) instead of properly preparing them in the PHP code at the point where the template variables are created. That is terrible for maintenance and the further use of your templates, because you have to replicate that PHP soup into every new template again. After all, you want to have a template engine so others can create new looks for your product, without having to know how to program it.
Third, with the templating engine based approach you have the possibility to add caching where necessary without any additional work. Not possible with the scripting approach. Yes, in a web application you won't be able to cache that much, but with a lot of data, there will be instances where it will help the user experience.
Fourth and least important, it makes your template less easy to export to other applications, and import templates from other applications.
The CSS Zen approach mentioned by Sohnee is great for websites, but is going to be too limited for a web application that uses complex input elements, JS based menus, and the like. It is too often that those elements need to be changed and customized in the markup.
If you have a look at my CodeIgniter Template library it briefly explains how you can set up themes and layouts (the equivalent of header & footer).
If you set up global code such as a Hook or a MY_Controller then you can dynamically set your theme based on the logged in user, the user type, etc.
Eg:
if($user->role == 'admin')
{
$this->template->set_theme('admin_skin');
}
else
{
$this->template->set_theme($user->theme);
}
That is just a VERY basic example of the sort of thing you could use this Template library for.
CMS Solutions
Magento and Wordpress package all theme related files into their own seperate directories. These contain the serverside code, stylesheets, images and javaScript for the theme. The user in effect chooses a directory to use which affects how the page is layed out and styled.
An easier approach
A much easier way to get started would be to accept that the actual content, e.g. HTML of a page would stay the same, but let the user choose from various CSS style sheets.
When choosing a style sheet the system could use JavaScript to load it in dynamically so that the user can preview the look they are choosing.
If you have really good semantic HTML it will be enough to change the CSS files. Unless the design changes are really heavy. Then it would make sense to provide PHP templates that are build with some sort of modules: variables which contain certain HTML structure like navigation or sidebar, etc.
For themes you do not need PHP. Just define your themes in CSS (the best way is one file for each theme) and use a simple JavaScript chooser like at this site: http://www.fotokluburan.cz/switchcss.js.

Categories