Implementing master pages functionality. PHP - php

How to make master pages in php? Like a Layout.cshtml (and RenderBody()) in ASP.NET MVC?
Thanks!
P.S. Maybe there's a third-party tool for the purpose?
EDIT
Ok. The thing is not about MVC architecture! Do look here: http://jsfiddle.net/challenger/8qn22/109/
I want the master page/layout to stay when user gets redirected to the other page
Want an average page to be nested inside the content division. So if it is a form I want this form to be displayed like: http://jsfiddle.net/challenger/XgFGb/17/

Here's what PHP standard framework/api supports:
The require("/definitions.php") function loads class, function and constants defines from a file and outputs the content outside of PHP code to php://stdout (on a webserver this is what is sent to the browser). You might wanna use require_once for importing dependencies (php files with definitions).
Use the PHP's open and close tags to obtain something close to templating functionality.
For example a normal page would look like this:
while an included (and repeatably includable) one could look like this:
I'm not saying "don't use templating engines", just showing a clear and simple way of achieving things which PHP is purposely built for. If this is enough for you needs, I then do say "don't use templating engines for the sake of it" (btw, if you are tidy, you can easily separate logic from views, without strict and sometimes cumbersome MVC frameworks).

Off hand, I know that the Laravel framework includes the Blade templating engine. It uses a syntax very similar to Razor.
Example:
#layout('master')
#section('navigation')
#parent
<li>Nav Item 3</li>
#endsection
#section('content')
Welcome to the profile page!
#endsection
(Razor, Blade, loller skates)

In PHP, there is a very similar technique called templating. Instead of a master page, you have a template. The language itself has no built-in templating features, but there are third-party templating engines (Smarty, PHPTAL, and XTemplate, to name a few).
If you want to have "real" master pages, it is entirely possible to implement them. Just wrap you master page into a class and include() that class into your content pages.
Also Zend Framework supports a two step view, where a view template is rendered inside a layout template. I think this satisfies your need for master pages.
See following links:
Approximating Master Pages in PHP
Is there anything like MasterPages on CodeIgniter Framework?
PHP Equivalent of Master page in ASP.NET
ASP.Net MVC or Zend Framework. What is your opinion
http://hoolihan.net/blog-tim/2008/09/24/simple-masterpages-with-php/

The Twig template engine offers Template Inheritance
The most powerful part of Twig is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.
Can be used as a standalone, but was made by the people behind the popular symfony framework.

A while ago (several years), I achieved something like this using Smarty, and extending it to contain a method to the effect of DisplayMaster("NameOfTemplate", "NameOfMasterTemplate")
It works by rendering a template and passing the result into another (master) template.
Above has 2 templates:
NameOfTemplate, just has the main content section, e.g.
<div>...{$someProcessing}</div>
NameOfMasterTemplate has the outer html
<html>...<body><div class="layout">{$innerHtml}</div></body></html>

Ok. The solution that suits me the best is described here http://www.phpro.org/tutorials/Introduction-to-PHP-templating.html#9. It is easy, fast to imlement and doesn't enforce you to use a templating engine. Cool!

Add this piece of code in the content area of your master.php file...
I am using it like this and it perfectly working for me
<li>BLOG</li>
<div class="container content">
<?php
if(isset($_GET['page']))
{
$page_name = $_GET['page'];
include("/".$page_name);
}
?>
</div>

Related

CodeIgniter Does Not Require a Template Engine

Please explain what a template engine is, and what it is used for. What are the paragraphs below trying to say? I don't follow the author's explanation.
Although CodeIgniter does come with a simple template parser that can
be optionally used, it does not force you to use one. Template engines
simply can not match the performance of native PHP, and the syntax
that must be learned to use a template engine is usually only
marginally easier than learning the basics of PHP. Consider this block
of PHP code:
<ul>
<?php foreach ($addressbook as $name):?>
<li><?=$name?></li>
<?php endforeach; ?>
</ul>
Contrast this with the pseudo-code used by a template engine:
<ul>
{foreach from=$addressbook item="name"}
<li>{$name}</li>
{/foreach}
</ul>
Yes, the template engine example is a bit cleaner, but it comes at the
price of performance, as the pseudo-code must be converted back into
PHP to run. Since one of our goals is maximum performance, we opted to
not require the use of a template engine.
A template engine is simply a way to embed your back-end code into your html. This is more common in languages like Python and Ruby than PHP since PHP already supports embedding within html code.
That specific templating engine may be easier for those coming from other back-end languages, particularly Python or Ruby since Django and Rails have very similar-looking syntax for templates.
While not necessarily a "template engine", I typically organize my Codeigniter projects where I have a template.php view that contains the skeleton layout and the content of each page of the site/application is a separate view that is loaded within the template.php file. This way I am not rewriting code on each page.
Template engines are all about personal preference--they aren't needed, but some people feel more comfortable using them if that's what they are used to. And people are more effective the less they have to think about their workflow!
In CodeIgniter Userguide describe that CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to use one.
But if u want to use template, I suggest to use this library that it is very simple.
http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html

What is the equivalent of Master Page and Web User Control in PHP?

Assume that I have some advertisments that I want to put in specific area of my pages. In ASP.NET I would use Web User Control for this pupose. What about in PHP? The same question for Master Page.
The "master page" and "web user control" are classes that are specifically provided by the ASP.NET framework. Just as these capabilities are not native to the languages of Visual Basic or C#, neither are they native to language of PHP - they must implemented on a framework level.
You could certainly do it yourself, however if you're looking for an ASP.NET-like experience in PHP then I suggest you look at the Prado framework, which is very similar and implements many of the features that you've probably used.
There is no such concepts in PHP. I think that it may have some frameworks that implement it, but I don't know wich. Or you can code it by your own :)
I suppose you could do it by putting them in include tags or required
e.g:
<?php
include ('global/header.php');
//Main content goes here
include ('global/main-right.php'); //Adverts or such
include ('global/footer.php');
?>
Where global is a folder containing files used on several pages
There is nothing similar, but you can implement such feature yourself, create header, footer, sidebar and... pages and in other pages include them.
One PHP project that does this well is PPI.
Here is an example of your "master template" which is has historically been named template.php
Folder: https://github.com/dragoonis/ppi-skeleton-app/tree/master/App/View/default/
File: https://github.com/dragoonis/ppi-skeleton-app/tree/master/App/View/default/template.php
If you look at line 28 you'll see the footer content. So say you wanted your widget/"web user control" to be in the footer then you can simply add
include($viewDir . 'controls/footer_control.php');
It's that simple, and will be included in every page load.
Good luck with your search,
Regards,
Paul Dragoonis.

PHP equivalent to site.master?

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.

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