PHP equivalent to site.master? - php

One of the nice things about ASP.Net is the ability to set a site.master file that holds all the repeated HTML/code from a site, and still be able to alter things on it from an individual website page. (For example, changing the <title> tag for every page, or adding other things to the <head> of your document.)
In the past in PHP I've used Server Side Includes to remove duplicate HTML/code (such as the top of the document, main navigation, footer, etc.) but obviously you can't alter any of the contents from the page.
Is there any way to implement site.master type functionality in PHP? If not, what's a good way to remove repeated HTML/code while still being able to change things like the page's title, highlighted navigation, etc.
Thanks.

This is just called Template Engine and there is tons of engine for php.
Smarty is one of them

The simplest way of pulling in common fragments is to use require() which will allow you to include other files within the current file.
An example of how you might use it:
header.php - a reusable fragment
<div class="header">
<h1><?= $pageTitle ?></h1>
</div>
pageContents.php
<body>
<?php
$pageTitle = 'Check it out, the Foobar page!';
require('header.php');
?>
blah blah
</body>

What you are looking for is a templating engine built for PHP. ASP is a framework which has templating built in which provides you the functionality that you are referring to (i..e templates, membership provider, etc.)
In order to get the same in PHP you will need to use either a framework or a templating engine.
Some samples:
http://www.webresourcesdepot.com/19-promising-php-template-engines/
http://www.phpframeworks.com/

there is no such functionality in PHP, you can move your components into separate files and include them in your main file using include or require functions.
Some frameworks do provide (simulate) such functionality though. e.g. In cakePHP you can have a layout file where you can output your pages.

Related

Updating pages easily with HTML

How can I update multiple pages when editing one page? For example, I am editing index.html, and I am changing its footer (which all other pages have). When I change the footer I want the other pages on my domain to be updated as well. Thanks!
This is a major reason why platforms like PHP and ASP.NET exist; they can help you dynamically generate HTML containing common sections like headers and footers that are defined in one place. One simple alternative that may be available for you is Server Side Includes.
Update:
Since you said you're using PHP, rather than having pages with the .html extension, you should write your pages in PHP. That way, you can include separate files containing your headers and footers in each page, so any changes to those only have to be done in one place, i.e.:
<?php include 'header.php'; ?>
<!-- Your page-specific content -->
<?php include 'footer.php'; ?>
There are a few ways to do this. You can use an editor that opens files of a certain project, and use regular expressions to edit.
Or a more common way to achieve this is to use SSI's or Server Side Includes (http://en.wikipedia.org/wiki/Server_Side_Includes). This is more common, and less likely to destroy pages if a regular expression isn't formed properly.
If you're using a different engine (like PHP) you can do something like file includes (require_once, include, etc), to pull the information from a single place. This is similar to SSI's in concept, except it requires another engine to parse the page.
Modern day IDEs for Web Design (DreamWeaver) include this type of functionality within them too. You only need to set it up.
For such automatic updating you can create a function in PHP
function generate_footer() {
echo "<p>Page maintained by Lucifer</p>";
}
and in the HTML code you just have to write this
<div class= "footer">
<?php generate_footer()?>
</div>
this is in php you can use any other server scripting language you wish

Dreamweaver Templates Equivalent

I have been using Dreamweaver to build several sites. In particular, I utilize its templates to manage consistent layout / design throughout each site.
In a nutshell, it works like this:
Create a template, for example:
<html><body><h1><!-- Marked as editable region. --></h1></body></html>
Create a new page based on the template
<html>body><h1>Hello World!</h1></body></html>
So, if I need to change h1 to h2, I'd simply edit the template and all pages based on it will get updated automatically: simple. The question is how do I do this without depending myself on a proprietary application like Dreamweaver?
I am hoping a simplest possible solution. By simplest I mean, I hope I don't need to build a CMS or something. :)
Thanks!
Update:
Can we do this using e.g. PHP?
There are tones of several ways to do what you want.
Let's start from the Apache level:
In case your web site run under apache you can use a module called SSI. SSI Stands for Server Side Includes. This is the simple way if you like to create template like web sites with HTML. The method allows you to split you web page into several files and then the server will compose all these into one page. So you can have in example a header.html footer.html sitebar.html about_us.html and when you call the about_us.html the server will load also the other three files into that one.
Using PHP require(_once) or include(_once):
PHP have four commands that allows the developer to load external php files into the current working file. So in example you can have the files header.php, footer.php about_us.php. and into about_us.php you can include the external files. Consider that as an example:
header.php
<html>
<head>
<title>My page title</title>
</head>
<body>
footer.php
</body>
</html>
about_us.php
<?php
require_once('header.php');
?>
Enter here HTML for your about us page
<?php
require_once('footer.php');
?>
Using a template Engine:
You can use a template engine like smarty. That engine requires PHP and is somehow difficult to use it. This is the most famous template engine for a long time now.
Using a programming language framework:
You can use a programming language framework, such us CakePHP that allows you to split your theme and create your own theme.
This list can be a really long. For now I thing you are ready to go with the most famous methods for templates ;)

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

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.

How to use Zend Framework for layouts only?

I was recently brought on to help with a project that was made up of individual HTML files with the exception of a PHP contact form. So there's not even a hint of object oriented programming, MVC, or layouts (or even PHP for that matter).
The project is quite large, but I wanted to slowly integrate the Zend Framework into this project, mostly to start using layouts. There are so many redundancies that it is such a waste of time to make small updates that should have been made in one file.
In the early days of PHP, you could separate your content blocks by including them in each page (a header and footer for example). Now, using MVC frameworks like the Zend Framework, you can create layout files that include the individual page content (views) using a view helper. I really like this because it means I only have to "include" my header, or footer, in one place.
However, I'm not sure how this would work without dispatching/bootstrapping the application (i.e. using the Zend Framework MVC components as standalone components instead). What would be the best approach to switching the site over to use layouts? How would it work? Is this even a good idea?
I've recently begun a transformation of a mish-mash file structure* to make use of ZF's layout & views. The goal is to move all files containing html into the recommended file structure for layouts and views. This is how to prepare for it:
Extract all markup from each file, keep variables in it but no logic. Name this file /application/views/scripts/page/view.phtml (for example /application/views/scripts/index/login.phtml)
Create a skeleton that fits most pages as /application/layouts/scripts/layout.phtml and let it contain something like this:
<?php echo $this->doctype('XHTML1_STRICT'); ?>
<html>
<head>
<?php echo $this->headLink(); ?>
</head>
<body>
<div id="wrapper">
<?php echo $this->layout()->content; ?>
</div>
</body>
</html>
(Add Zend to your include path and register its Autoloader.) Create a file that will be included in all of your files (unless you have a single point of entry, in that case - place it there!) Create a reference to your layout, equivalent to this:
$view = new Zend_View();
$view->setScriptPath('/application/views/scripts');
$layout = new Zend_Layout();
$layout->setLayoutPath('/application/layouts/scripts');
$layout->setView($view);
Zend_Registry::getInstance()->set('layout', $layout);
Each php file you have left (with logic, not html) needs to have access to the layout, and modifying it:
$layout = Zend_Registry::getInstance()->get('layout');
$view = $layout->getView();
$view->headLink()->appendStylesheet('/css/a_css_file.css');
// most important step, done automatically when using MVC, but now you have to do it manually
$layout->content = $view->render('index/login.phtml');
echo $layout->render();
Most important next step is adding another layout:
// /application/layouts/scripts/blank.phtml
<?php echo $this->doctype('XHTML1_STRICT'); ?>
<html>
<head></head>
<body>
<?php echo $this->layout()->content; ?>
</body>
</html>
and in one of your logic-containg files
$layout = Zend_Registry::getInstance()->get('layout');
$layout->setLayout('blank');
Ideally, in a near future you can start adapting to a MVC-like structure by looking at a design pattern like Front Controller.
*One file: model, controller, html, in no logical order.
You can certainly use Zend_Layout in isolation and it's detailed in the manual:
28.2.3. Using Zend_Layout as a Standalone Component
I believe you would then need to capture you script's output via output buffering, and pass it to the layout to be echoed.
This situation is not ideal, and without moving to the full MVC I'd probably recommend using a different, basic templating system or following the advice in other comments here.
Personally, I'd recommend not using the Zend Framework if you're only planning on using it for template/layout management. There are much better solutions for templating with PHP, with Smarty being the obvious choice (formerly part of the PHP project).
Smarty does provide a reasonably easy integration with the Zend Framework, if you need to do this at a later date, and there are a few articles on it on the Zend DevZone.
I'm not sure if this is what you're looking for, but the bbc has some videos where they use parts of the zend framework without using the whole MVC. I think they are in parts 4 & 5, http://bbcwebdevelopers.blip.tv/
Zend_Layout isn't really about including a header or footer, rather it is best used to insert various bits of content into a single large template. It's pretty sophisticated and as well as common use cases such as inserting the main body of content you can insert HEAD tags such as CSS, scripts or title tags and custom placeholders such as navigation.
From your description I'd go for a simple PHP include header and footer solution. It will be easier to implement and will remove any duplication of common template elements.
If you really want to use this to learn Zend Framework you could use Zend_Layout in the standalone mode as dcaunt suggests. There is no point trying to use the MVC bootstrap system since your site doesn't appear to need it. I'd simply do something like use URL rewriting to send all *.html requests to a single PHP file which then starts Zend_Layout and loads the requested file into the $layout->content variable via something like file_get_contents()
You could then also use ZF for the form processing if you wished.
i dont think you can do this by default, i think you need to use the Zend View as well.
But i am sure you can modify the Zend_Layout to work with your existing setup. Sorry i cant be more specific on how to do this, because it depends a lot of what is currently in place.
As a starting point i recommend looking into Smarty integrations into Zend to see how you can modify it.

Categories