How to structure php that generates html - php

I have a php file and a bunch of HTML elements that include:
header
css
a "spacer" element used repeatedly, static
a bunch of templates that will take arguments from the PHP code for what to insert
Basically I'm wondering what the right way to factor all these files in. I'm guessing I should have a file.css in my folder that the php will slurp up into memory and drop in the header information. Should the spacer element be saved as "spacer.html", and the PHP will slurp up one copy of it into a string and drop it into the HTML as necessary? Or should all of these just exist as string constants in the PHP?
It's a little trickier for the dynamic "template" elements because I'm not sure how to separate the HTML and let it have markers that the arguments get dropped into.

You should look into MVC. A popular one right now is CodeIgniter. The idea is you take those HTML "templates" and create (V)iews. PHP uses a (C)ontroller to direct the user and call on (M)odels to fetch data, then send the appropriate variables to the (V)iews for the browser.

I've noticed some of the other answerers (SP) mentioned MVC. MVC is incredibly important because it allows you to separate your business logic from your "view" display/UI layer and your database logic from your business logic.
Like, AlienWebguy, I'd recommend Code Igniter, but there are a number of other good frameworks out there for PHP.
As far as what it appears that you're asking is how you should structure both your view layer and business logic. If I have something common like a header and footer, I'll put them in
view/include/header.php
and
view/include/footer.php
The header file will generally contain the <html> tag, the style sheet link(s), any common javascript script files, and a common header (like the logo and navigation). The footer file will generally contain the copyright info, any footer links, and the </body></html>.
Generally what you should look to do in creating your views effectively is to have them process model objects to display the HTML, and generate absolutely no HTML in your controller layer. E.G.
<table>
<?php
foreach ($users as $user) {
printf('<tr><td>%s</td><td>%s</td></tr>', $user->id, $user->user_name);
}
?>
</table>
Doing that makes things a lot cleaner by avoiding interspersing concerns at the wrong "layer".
The other thing you can do, if you're not interested in writing straight PHP in your views, is you can use a templating engine. Code igniter includes support for (but you don't have to use) a template engine.

I usually suggest using some good ol' php includes to tackle this.
File structure wise, I'd probably have an index.php file -- which (without knowing much about your templates in #4) would outline the page. You could call in the header.html page or put the header right in the index.php file.
The css file would best be named: style.css (this is pretty standard) and you can call that from your header file.
Not sure if you're getting at this, but you can include HTML in a .php file. You'd just name the file something like: index.php and then your code can be:
<p>This is HTML.</p>
<?php echo("This is PHP."); ?>
And intermix them throughout.

Related

Interchangability of PHP and JavaScript templates (prevent duplication)

I use a MVC PHP framework to keep my web applications as DRY as possible. All of my HTML templates are neatly tucked away in one folder in the application scope of my project.
The problem is that whenever I use a JSON string to build a page with AJAX, I need to reuse a lot of lines from these templates and copy them somewhere in my JavaScript files. This means there is code duplication between templates in my JavaScript files and templates in my PHP application.
I was wondering how this duplication can be prevented. One way is of course to load the template using AJAX, but then I would end up with a double AJAX request for one page. Furthermore, the PHP templates uses different tag styles to represent variables than MooTools, but the HTML setup is the same.
So to summarize: is there any neat way or a tool to prevent duplication of templates so one file could be used in both PHP and JavaScript? For the record: I use the MooTools framework to build my JavaScript files.
Edit
After some research, I found the best answer yet in my opinion. For those who are interested:
PURE
PURE separates HTML representation and JavaScript logic completely so you don't have to bother including HTML elements in your scripts. The template can simply be provided in the HTML file itself.
Example:
// JSON string
{ 'who': 'me' }
// In your rendered HTML page:
<div id="who"></div>
// After the JSON string is sent back
<div id="who">me</div>
Furthermore, it can be used by a wide selection of libraries: MooTools, jQuery, dojo, Prototype etc.
Interesting question that I'm struggling with sometimes too.
you can put your html in your javascript code, which is duplicating and which you want to avoid
you can load your html with a separate ajax call, which causes more ajax calls to be run, and possible slowing down of your app. you may want to avoid it.
you can pass your html within the Ajax call that will load the data. That way, you only have one call. Let your PHP open your templates, and add them to the data-json stream.
you can put the template inside your original html, put it as hidden.
I'd go for solution 3, or possibly 4 if templates are small and limited.
The JSon would then be something like {"data": ... your original data object, "templates":{...}}
You might be looking for a template langugage that is available for multiple languages so you can re-use your templates across language boundaries.
One such template language is {{mustache}}, works in both PHP and Javascript and many more languages.

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 :)

where to place the php code?

i would like to know your point of view on where to position the PHP code on .php page and why?
a) top of the document
b) just above the html elements where i am going to use it.
thank you.
c) In a different file and use a template engine such as smarty
http://www.smarty.net/
Your life will be beautiful and awesome after smarty.
EDIT : I won't downvote other solutions , but it's a very ugly anti-pattern to mix html code with php, you have good, stable and easy solutions to avoid that, use it now or your website will be a big mess of spaghetti code.
Depends on the purpose.
Database query related posts that determine the contents within the part, I call it before there is any input. Also any type of PHP commands that contain raw header information should be presented before any output is made.
Any content related stuff can be positioned anywhere on the page. PHP code is really everywhere - where ever, and however you want to create the HTML from your PHP dynamically.
My pages usually take this structure:
<?
include 'start.php';
$pagetitle = 'the services we offer (branding, web, print etc.)';
$metatitle = 'Our Creative Services (branding/logo, web, print)';
$scriptinclude = 'whatwedo.js';
include 'header.php'; // contains the <body><head></head><body> and a few more elements to start the header/menubar etc.
?>
<div class="full_grid" id="index_slide">
// content here, mixed with PHP if you like...
</div>
<?
include 'footer.php'; // contains the footer HTML, as well as </body></html> etc. to wrap things up.
?>
I put as much code as I can at the top. And only use php withi HTML where I need loops or output data.
This gives me a better overview of the code and it's easier to work with.
Keep your code and HTML as separate as possible. Have them in entirely separate files where you can.
Your HTML should be as much pure HTML as possible, and your PHP code should contain as little HTML as possible.
Obviously, you're producing a web page, so there will have to be some mixing, but keep it as limited as possible: The only code you should mix in with your HTML should be the one-liners to place specific bits of PHP-generated code into your HTML template.
It completely depends what you're doing with it. Personal preference for me is to create any functions I need at the top and then scatter inline php throughout the document calling the functions at the top of the page.
If something needs calculating and it can be done at the top, it's much easier to read and debug if you keep it all in one place. And keeping this the same throughout all your files will help too. What you could do is just include a config file at the top of the page with any site-wide functions you need too, so you don't have to copy and paste through all your files.
If you are only using one PHP file then definitely put all PHP code at the top, then the HTML below with variables where necessary.
For example, $title = 'Page title'; at the top of the page, then <h1><?=$title?></h1> in the HTML portion of the page.
However a better solution is to have two (or more) files. The main one contains all the PHP logic to grab/process data, while the second one is a "view" file containing mostly HTML. The simply include your view file from the main PHP file.

HTML coding and mixing of PHP or JavaScript code

I am assigned a task to revise a website and at present, I am working on index.html page. the previous coder has mixed a lot of JavaScript and CSS code in between and it is becoming difficult to read.
I want to know whether it is necessary to include <script> tags and CSS code in between? What about PHP code? Where each must reside?
Edited:
If multiple JavaScript and CSS files are to be referenced, how to include in a single <script> or <link> tag?
Keep your JavaScript inside a separate file, keep your CSS inside a separate file and have them both referenced from within your HTML. The order of these referenced files relative to the HTML does not matter. As for the PHP, I wouldn't worry too much about it being mixed in with the HTML (just keep your functions, classes and other scripts in separate files and include them with PHP in the header).
If is the same CSS on each page, having an external file that caches help to save bandwidth. If there are different rules intermixed with the HTML for different element types you may have some conflicts, but if you rewrite it, it will end up being a lot cleaner and easier to maintain later.
I like to keep a file structure like so:
index.php
/css
main.css
othercssfiles.css
/javascript
main.js
otherjsfiles.js
/template
header.php
footer.php
/scripts
functions.php
otherscripts.php
Then in my header file, I would place HTML code referencing the files in the CSS and JavaScript directories. And in the root directory my index.php file would include(); the header at the top and the footer at the bottom.
otherjsfiles.js and othercssfiles.css can be used in cases where a single page may have a specific requirement, requiring a lot of CSS and JavaScript that most other pages don't need. It means other pages do not need to fetch unnecessary data and it keeps page specific code separate from the entire site's code.
I have found this an easy way to keep track of various aspects of the code that makes up an HTML page, but naturally, you will find ways to organize it that makes sense to you.
Edited:
If multiple JavaScript and CSS files
are to be referenced, how to include
in a single or tag?
It would be better to combine them into a single file to conserve HTTP requests (which take time). Then you would just include those CSS and JavaScript files like normal.
<script type="text/javascript" src="/javascript/main.js"></script>
<link rel="stylesheet" href="/css/main.css">
Additionally, it seems like you could use the services of a CSS beautifier for readability, a JavaScript beautifier for readability and a JavaScript minifier for when you are done reading it (keep the readable version) and want to save bandwidth. These tools are especially helpful when you are working on maintaining a website you did not create.
Rarely is there a valid reason for CSS be mixed into the HTML - a separate file is generally best.
With JavaScript: there may or may not be a good reason for it being mixed into the code. E.g. if a piece of script is dependant on running after one element of HTML is loaded and before another. This isn't a particularly good coding practice, but if you're updating an existing site you may be stuck with it.
In the end the only way to really tell is to pull it out and make sure the page still works.
As Sam said, keep JavaScript and CSS external, and reference items in the JavaScript by id rather than onclick= etc. Follow Yahoo, and put the CSS in the <head> and the JavaScript before the closing <body> tag.
For multiple JavaScript or CSS, use multiple <script> or <link> tags.
As for PHP, it's good practice to keep as much of the functionality in a separate include file, and just call functions etc. in the main HTML. This will aid maintainability greatly. Aim for simple loops, if/elses, and function calls, and nothing else.
If multiple javascript and CSS files
are to be referenced, how to include
in a single or tag?
You either reference each file using multiple tags or use a minifier like YUI compressor to create a single CSS and JS file from the originals.
The order of CSS styles is relevant, but only relative to other CSS styles. So, start by moving all CSS styling together (in the head section) in the same order as originally. That will make it somewhat less messy while defenitely not changing how the page works.
Then you can start looking at whether you can rearrange scripts and PHP code. What they output to the page directly is relevant, otherwise they can easily be rearranged.
PHP coding allows you to have HTML/CSS interspersed with PHP code by using server tags like <? -php code here -?>.
This is normal - it is very flexible and easy-to-get-started.
Your JavaScript should ideally be placed into a separate JS file and using the <script> HTML tag to reference it. See the docs.
Your CSS should ideally be placed into a separate CSS file and use a <style> HTML tag to reference it. Again, see the docs.

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