Basic Templating in PHP!

steve
0
6th September

How to make use of templates within a PHP application, without using a complex templating engine.

php logo

In small projects it’s easy to fall into the trap of quickly creating PHP interspersed with markup, writing code in logical sequence, but losing the separation between presentation and business logic.

No matter how small even for single page sites, it’s always a good idea to try separate the two. The most obvious practical reason is as the site expands in size and complexity and as the inevitable visual changes are requested by the client, it’s much quicker and easier to change a well laid out application with this logical separation of code and design. That is to say it’s a good idea for the benefit of extensibility and maintainability.

Although for a basic deployment it can often not warrant the time or bloat of a fully fledged templating engine, say a PEAR or Smarty solution.

Basic templating is still available using standard PHP functions and without the need for a complex templating engine. Allowing small application or website to adhere to the basics of MVC (Model View Controller) design pattern (mainly the V and C part of that). The following also provides an easy way to still use templates for emails as well as standard output for the browser.

Here’s how

To start with it’s a good idea to separate the files themselves, putting all the visual or view files into a separate folder by themselves, making it easier for others(or yourself at a later date) to find.

For example:
/index.php
/templates/index_view.php

While often the file extension of the template file can be changed to allowing easier identifying (say .tpl) for small quick deployments leaving it as .php means that no server configs need to change to allow it to run correctly and stop it from been inappropriately viewed.

Now include in your index file all the applications/sites logic.

Include in your index_view file all the HTML or visual based markup. Where a dynamic variable is required use php to echo it out. For example or

While you can include the template file in scope in your php file, it’s neater and more flexible to create a separate function to complete this task (or if appropriate and as it becomes more complex a separate Class may be desirable). In addition this step is required if you wish to use the templates for email.

/**
*
*  Apply template parse view file, store and return output.
*
* @param $template_name String The name of the template file without it's folder or file extension.
* @param $params Array Associative array of parameters required by the template file
* @return String the final output.
*/
function apply_template($template_name,$params) {
    extract($params);
    ob_start();
    include('./templates/'.$template_name.php');
    $content  = ob_get_contents();
    ob_end_clean();
    return $content;
}

The above is a basic function that will set local variables with the name of the key in the associative array of params, include the template file in this scope, capture output and return as string.

Below shows how this may be used with an example of the index.php and template index_view.php files.

In index.php

/** PHP file to get a string and output it **/
$msg_str = 'Hello world';
$params = array('message' =>  $msg_str);

$template_name = 'index_view';

$output = apply_template($template_name,$params);

echo $output;

In index_view.php

<?php
/** PHP File to display a name **/
?>
<html>
   <head>
      <title>Message Output</title>
   </head>
   <body>
      <h1>Example Template</h1>
      <p><?= $message; ?></p>
   </body>
</html>

That’s it for the basics, extra loops and where necessary conditional statements may be added to the template file to make it more powerful but avoid crowding it with any business logic, try keep it as neat and pure HTML as possible.

In addition where the above can be extra useful is rather than echoing it out as is, the output from can be used as the HTMLl email content.

For example:

$output = apply_template($template_name,$params);
mail($to, $subject, $output, $headers);

Forrst: A Community for Designers and Developers Alike!

Nick
2
14th February

Forrst logo

Forrst is a community for developers and designers exclusively. In fact, the team at Forrst are adamant on only including passionate designers and developers, which may or may not give you a tough time finding an invitation if you’re interested in joining. This is what makes Forrst such a great community to be part of however. It’s a place for sharing work and inspiration, getting valuable and constructive feedback, and ultimately improving your skills among people with the same enthusiasm as yourself.

Sharing on Forrst is done through user posting, which may take the form of questions, code, snaps (images), or links. You can share pretty much anything you find interesting to other developers and designers, including work in progress that you need feedback on. You may also follow other members to keep updated with your favourite contributors via your homepage news feed or you find specific topics by searching posts by category or other criteria, such as most popular. Want to share your posts with friends that don’t have a Forrst account? No problem. Just blog, tweet, HackerNews, or share the short URL for any public posts you own and you’re done.

More recently, Forrst announced that it’s going to release a “pro account” offering some great benefits to users wanting to take their membership to the next level. Some of these features may include: a monthly allotment of acorns, access to a pro members only discussion room, a stats dashboard, custom domain support for Forrst.me, a pro profile badge and early access to new stuff.

All in all, this is a great community to be part of if you take your design and development seriously. It’s an incredible way to keep yourself up-to-date, learn, teach and see what other people are working on. Head on over to Forrst to learn more and apply for a membership. Also, follow @forrst or @forrstpodcast on Twitter!

Cross Browser CSS3 Using CSS3 PIE!

Nick
0
26th September

CSS3 Pie LogoThose of us already dabbling in CSS3 and HTML5 are enjoying the benefits that these technologies bring to modern design. Unfortunately, for many this has come at the cost of countless ‘hair pulling’ hours spent hunched over our workstations attempting to achieve some cross browser stability in our designs, namely Internet Explorer.

That’s right; every designer’s favourite browser is serving up some serious CSS3 headaches for all of its current versions. There is light at the end of tunnel however. When it is fully released at some point this year, Internet Explorer 9 will support most of the latest CSS3 behaviours and decorations. Bu until then, we’re still stuck with doing our best for IE users.

CSS3 PIE comes to the rescue!

CSS3 Pie allows your CSS3 properties such as border-radius, box-shadow, border-image and so on to display correctly in Internet Explorer web browsers, versions 6-8. It is a relatively new library developed by Jason Johnston that cleverly creates DHTML behaviors that IE can understand, and then it controls how they’re presented. Best if all, it’s Open Source!

The PIE stands for Progressive Internet Explorer. I’ve had the opportunity to implement this tool into some of my current work and couldn’t believe the great results. It’s not perfect, however, PIE currently has full or partial support for the following CSS3 features only, with other features under active development:

  • border-radius
  • box-shadow
  • border-image
  • multiple background images
  • linear-gradient as background image

How to use it

Download PIE and upload the file named PIE.htc to your directory. Now, every instance that you use a CSS3 element, simply place behavior: url(path/to/PIE.htc); in your CSS file along with the other CSS3 browser prefixes for that element. That’s it, a piece of pie right! Your CSS3 element should now beautifully render across all versions of Internet Explorer. As an example, this should look something like this.

#CSS3Element {
border: 1px solid #999;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
behavior: url(path/to/PIE.htc);
}

There are a couple of ways to integrate CSS3 PIE into a WordPress theme. If you have access to the root folder then simply place the PIE.htc ( and PIE.php if required) at this level instead of within your theme directory. If you don’t have access to the root then Gordan Brander has a great tutorial using another method for WordPress integration.

All in all, this is great solution.It’s by no means perfect and, in fact, taking this type of approach to utilise CSS3 is controversial among some designers and developers. It’s definately worth while reading the known issues with using PIE as you will no doubt encounter one or more of these. I suppose this tool sits alongside similar ones you might have heard of or be using, such as Modernizr and html5shiv. I encourage you to try it for yourself and come to your own conclusion. Please feel free to let me know how you go!

On a sidenote, if you do find this tool helpful please consider a donation for Jason too. You can also keep up-to-date by following CSS3 PIE on Twitter.

Free Tools for Optimising, Validating and Checking CSS!

Nick
0
25th August

G Clamp

A Quick Guide…

We all know how important is for websites to load as quickly as possible, just ask your users. By taking steps to reduce your CSS files, you’re ensuring faster loading times, increased usability, higher user satisfaction and better overall website performance. This is not an article on the importance of validating and optimising your CSS files however, this is assumed knowledge. Instead, this is a quick reference to some of the best free, web-based CSS optimizers/compressors, code formatters, and validation services out there. Check them out and pick the ones that work best for you.

Validation and Checking

A CSS validator will basically check your CSS to make sure it complies with the CSS standards set by the W3 Consortium by pointing out errors, warnings and other issues. The most common web-based validation service for CSS is, in fact, the W3C’s own CSS Validation Service but there are several others. Here are the best, in my opinion.

Compression and Optimisation

Once you have completed checking the validity of your CSS and cleaned up any unnecessary code, it’s good practice to optimise and compress your CSS to help achieve the smallest possible file size. Although you probably strive to achieve well optimised code ’straight off the bat’ you’ll most likely won’t reach perfection first time around. These great tools will help you eliminate any bloat from your files without any tedious manual work.

Beautiful Javascript AJAX Loaders

Simon
3
23rd August

We are all familiar with AJAX loaders on websites, these are mostly animated gifs that are often placed and transitioned in and out with a little javascript. The problem with animated gifs is that they do not support alpha transparency and therefore when using a single colour transparency they can look less than polished over certain backgrounds.

Enter Raphael JS a javascript vector graphics library that even works with the dreaded internet explorer (and without the use of additional plugins). Raphael JS has a multitude of uses from producing basic vector text and images to image manipulation, animation, graphing and yes AJAX loaders. There are some great examples on the website, here are two that I have been using recently (Both of these are based on one of the examples available on the Raphael web site).


Aren’t they beautiful, even better they will look great over any background and because they are created programatically it is easy to tweak them and modify them into different forms.

The mobile web made easier with the viewport meta tag!

Nick
0
8th August

In a nutshell

Paste the following meta tag into your header and marvel at the wonders of this simple piece of code.

 

Smartphones

What is the viewport meta tag?

It’s no secret that the days of the mobile web are well and truley upon us. Only accessing the Internet via your desktop or laptop is a thing of the past. According to the Australian Interactive Media Industry Association, the use of mobile phone services has continued to grow in the past year as more Australians buy internet-enabled smartphones and other mobile devices like the Apple iPad. On a larger scale, it’s forecast that by 2013 there will be more than 1.7 billion mobile Internet users worldwide, by far outweighing the number of desktop and laptop users accessing the Internet.

With those kinds of numbers in mind, understanding optimal development and design practices for mobile devices has now become a staple for people designing and developing for the web. There are many ways to tackle the challenges of designing for mobiles but this is just one simple step you can implement to ensure some cross platform and browser stability in your designs.

Most mobile platforms assume different browser settings if none are specified, which can lower the quality and user experience of your designs on these platforms. Placing the viewport meta tag in the head section of your pages can override these default values and ensure your users receive a consistent and optimised experience instead of arbitrary results. The viewport meta tag is fast becoming popular for cross-device compatibility and we recommend exploring its possibilities. It is supported on many smartphones and tablets, from iPhone to Android to webOS (Palm) to even Internet Explorer Mobile, Opera Mini and Opera Mobile. Mobile Safari first introduced the “viewport meta tag” to let web developers control the viewport’s size and scale and now many other mobile browsers support this tag, and although it is not part of any web standard it continues to grow.

So how’s it work?

The first piece of this code, content=”width=device-width, controls the size of the viewport. What we’re doing here is setting the viewport width equal to the actual width of the device so that we deliver a width in CSS pixels at a scale of 100%, instead of the default 980px. A majority of new smartphones will have a width of 320px but this can change depending on the device. The viewport width can be set to a specific number of pixels like width=400px but in most cases it’s better to use width=device-width to deliver more consistent results that are device independent.

The initial-scale property controls the zoom level when the page initially loads. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out. Setting an initial or maximum scale means the width property actually translates into a minimum viewport width.

But wait, there’s more!

The viewport tag has more options to play with other than the width, so get experimenting:

PropertyDescription
widthWidth of the viewport in pixels (or device-width). If width isn’t set, it defaults to a desktop size (980px on mobile Safari).
heightHeight of the viewport in pixels (or device-height). Generally you don’t need to worry about setting this property.
initial-scale(0 to 10.0) Multiplier that sets the scale of the page after its initial display. Safe bet: if you need to set it, set it to 1.0. Larger values = zoomed in, smaller values = zoomed out
minimum-scale(0 to 10.0) The minimum multiplier the user can “zoom out” to. Defaults to 0.25 on mobile Safari.
maximum-scale(0 to 10.0) The minimum multiplier the user can “zoom in” to. Defaults to 1.6 on mobile Safari.
user-scalable(yes/no) Whether to allow a user from scaling in/out (zooming in/out). Default to “yes” on mobile Safari.

Why use jQuery plugins to create tabs when coding them is so simple

Simon
0
9th June

Here is a quick little tutorial on coding a set of tabs

First lets start with the HTML

<div id="tabs">
<ul id="tab_links">
	<li id="tab1" class="active">Tab2 Title</li>
	<li id="tab2">Tab1 Title</li>
...</ul>
<div id="tab_contents">
<div id="tab1_content">

Some Content

</div>
<div id="tab2_content" style="display: none;">

Some Other Content

</div>
...

</div>
</div>

As you can see the list elements will create the actual tabs with the tab content below. By default we want to have the first tab active (class=”active”) and hide all other tabs (style=”display:none;”).

Now for some css

ul#tab_links {
list-style:none;
color:#000;
margin:0;
padding:0;
z-index:1;
position:relative;
top:1px;
}
ul#tab_links li {
cursor:pointer;
float:left;
background:#ddd;
border:1px solid #bbb;
padding:5px 10px 3px 10px;
margin:2px 4px 0 0;
font-size:14px;
}
ul#tab_links li:hover {
color:#333;
}
ul#tab_links li.active {
border-bottom:1px solid #fff;
background:#fff;
color:#333;
}
div#tab_contents { z-index:0;
clear:both;
border:1px solid #bbb;
background:#fff;
padding:10px;
}

Finally the javascript

jQuery(document).ready(function() {
//Add a click function to all list elements within ul#tab_links
$('ul#tab_links li').click(function() {
//Remove the active class from all the list elements and hide all the tab contents
$('ul#tab_links li').removeClass('active');
$('div#tab_contents').children().hide();

//Add the active class to the clicked element and show its contents
$(this).addClass('active');
$('div#' + jQuery(this).attr('id') + '_content').show();
});
});

I have used jQuery (of course) for this example and below is a demo of it working.

Some Content

Tip: Easy Javascript Form Validation With jQuery

Simon
0
23rd April

Have you ever had a site where you have multiple forms that you would like to validate then submit via ajax and you would like an easy and consistent way of handling them – well this is it!

Step 1: Firstly lets start with the form.


<form id="theform" action="action.php" method="post">
<div><label>Field 1</label>

<input class="notempty" type="text" /></div>
<div><label>Field 2</label>

<input class="email" type="text" /></div>
</form>

*Note that the form has an id and that each field you want validated has a class added that specifies the type of validation to be performed.

Read the rest of this entry »

CakePHP, jQuery, Wordpress and Coding Goodness

Simon
0
7th April

social media bandwagonIn these posts I will be publishing code snippets, tutorials and plugins that I have used (or created) while making sites for Conduct HQ.

Primarily I have been using a framework called CakePHP (which I love), it is very flexible and once you have the database and frontend designed a MVC (model, view, controller) web application is easily created (baked),  following this process, the design can be applied and the application can be finetuned to the end product.  I am mostly using Cake 1.2 at the moment and have begun using Cake 1.3 which is nearly ready for full release.  Among many improvements Cake 1.3 now has native support for all javascript frameworks (not just prototype and scriptaculous) which is great as I prefer jQuery.

I use jQuery with various plugins, mostly for user interfaces and any ajax I need.  My favourite plugins at the moment are jQuery Tools and jQuery UI for excellent and easily configurable user interface components like modal boxes, sortable elements, datepickers, accordions and many more.  For easy ajax forms you can’t go past the jQuery Form Plugin.

Our company has also been producing iPhone applications and any time we need a web service for the application it is inevitably CakePHP that we use.  With Cake the creation of a JSON web service (or any other for that matter) is simple and straightforward, and with a little work creating a content management system or even a web application is also easily developed.

I have also been using Wordpress and its extensive list of community produced plugins for blogs and content management systems and even some small online stores.  There are many themes available and customising the themes or creating them from scratch is easy.  For larger online stores you cannot go past Magento which I am currently in the process of exploring more fully (and learning from a more experienced colleague).

Anyway I think that is enough of a summary for my very first post.  Stay tuned for more.