Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $9.99/month after trial. Cancel anytime.

Smarty PHP Template Programming and Applications
Smarty PHP Template Programming and Applications
Smarty PHP Template Programming and Applications
Ebook653 pages3 hours

Smarty PHP Template Programming and Applications

Rating: 0 out of 5 stars

()

Read preview

About this ebook

In Detail

Smarty is a templating engine for PHP. Designers who are used to working with HTML files can work with Smarty templates, which are HTML files with simple tags while programmers work with the underlying PHP code. The Smarty engine brings the code and templates together. The result of all this is that designers can concentrate on designing, programmers can concentrate on programming, and they don't need to get in each others way so much.Even if you are developing a site on your own, Smarty is a powerful way to make your code clearer to you and others, as well as easier to debug and modify later.

Visit the Free Online Edition for Smarty PHP Template Programming and Applications and learn more about the book and discover what each chapter from this book has in store.

You can now download "Smarty Cheat Sheet" for free: http://smartybook.packtpub.com/

Approach

Using a step-by-step approach based on realistic examples, the expert authors show you how to use Smarty in your own PHP development.

Who this book is for

This book is written for PHP developers who want to use Smarty templates in their development, and for designers who are working with PHP developers who are using Smarty.

LanguageEnglish
Release dateApr 30, 2006
ISBN9781847190284
Smarty PHP Template Programming and Applications
Author

Hasin Hayder

Hasin Hayder graduated in Civil Engineering from the Rajshahi University of Engineering and Technology (RUET) in Bangladesh. He is a Zend-certified Engineer and expert in developing localized applications. He is currently working as a Technical Director in Trippert Labs and managing the local branch in Bangladesh. Beside his full time job, Hasin writes his blog at http://hasin.wordpress.com, writes article in different websites and maintains his open source framework Orchid at http://orchid.phpxperts.net. Hasin lives in Bangladesh with his wife Ayesha and his son, Afif.

Read more from Hasin Hayder

Related to Smarty PHP Template Programming and Applications

Related ebooks

Information Technology For You

View More

Related articles

Reviews for Smarty PHP Template Programming and Applications

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Smarty PHP Template Programming and Applications - Hasin Hayder

    (missing alt)

    Table of Contents

    Smarty PHP Template Programming and Applications

    Credits

    About the Authors

    About the Reviewer

    Preface

    What This Book Covers

    Conventions

    Reader Feedback

    Customer Support

    Downloading the Example Code for the Book

    Errata

    Questions

    1. Introduction to Smarty

    Templating Systems

    Why Use a Templating System?

    The Smartness of Smarty

    Smarty Alternatives

    A Rough Guide to the Software Design Process

    Working in Teams: Layers and Separation of Concerns

    Smarty—The Ultimate Templating System for PHP

    Is Smarty Fast?

    Is Smarty Secure?

    Smarty’s Main Features

    Variable Modifiers

    Template Functions

    Debugging

    Plug-ins

    Filters

    Smarty Internals

    Installing and Configuring Smarty

    Step 1: Obtaining Smarty

    Step 2: Configure PHP to Find the Smarty Libraries

    On Windows

    On Linux

    An Alternative to Step 2: Using Smarty without Having Full Access to the System

    Step 3: Set Up Smarty for Your Application

    Step 4: Verifying the Installation

    Smarty Development Versions on CVS

    Upgrading a Smarty Site

    Summary

    2. Smarty Site Architecture

    Separation of Concerns

    What Does Concern Mean?

    A Problem-Solving Perspective

    Cross-cutting Concerns

    Roles Involved in Building and Maintaining a Website

    Starting a Smarty Project

    Directory Structure

    Securing our Smarty Project

    The Data Access Layer

    How it Works

    The Business Logic Layer

    How it Works

    The Presentation Layer

    How it Works

    The Result

    Summary

    3. What Designers Need to Know

    Development Team Problems: Common Scenarios

    Roles of a Template Designer and a Programmer

    Definitions and Concepts for Designers

    Concept of Reusability and Components

    Splitting into Components

    How to Design Table-less Layouts?

    Handy Built-in Tags

    Choosing an Editor for Template Design

    Collaborating with Programmers

    Summary

    4. Creating a Template

    Design Concepts, from HTML to TPL

    Introduction to Smarty Variables

    Starting Templates

    Non-associative Array

    Associative Array

    Passing Arrays to Smarty Templates and Manipulating Them

    Basic Templating

    Logical Conditions

    Loops

    section

    index

    first

    iteration

    total

    loop

    foreach

    Templates in the Real World

    Calendar

    Database Report

    Data Input Forms

    Email Newsletter

    Running PHP Code Inside your Templates

    Summary

    5. Advanced Templating

    Smarty under the Hood

    Compile Steps

    Prefilters and Postfilters

    What is a Smarty Modifier?

    Stretch your Imagination with Smarty

    Student Transcript

    Table Name: Grade

    Table Name: Courses

    Photo Gallery

    Available Modifiers

    capitalize

    count_characters

    cat

    count_paragraphs

    count_sentences

    count_words

    date_format

    default

    escape

    indent

    lower

    upper

    nl2br

    regex_replace

    replace

    spacify

    string_format

    strip

    strip_tags

    truncate

    wordwrap

    Combining Modifiers

    Configuration Files

    Summary

    6. Smarty Functions

    Types of Smarty Functions

    Functions in Action

    Action: Re-using Page Elements with the include Function

    Explanation

    Inserting Dynamic Content

    Passing Variables to Included Templates

    Saving Variables in Configuration Files

    Creating Configuration Sections for Each Page

    Handling Lists in Templates

    Removing Extra White Space from Templates

    Handling JavaScript Code in Templates

    Processing Deeply Nested Arrays

    Cycling Through a List of Values

    Avoiding Spam Indexers

    Form-Related Functions

    More Form-Related Functions

    Summary

    7. Debugging for Designers

    Debugging Smarty Templates

    Semantic Errors

    Common Smarty Errors

    Other Common Smarty Errors

    Smarty Debug Console

    Summary

    8. Built-in Smarty Variables and Methods

    Built-in Smarty Variables

    $template_dir

    $compile_dir

    $config_dir

    $plugins_dir

    $debugging

    $error_reporting

    $debug_tpl

    $debugging_ctrl

    $compile_check

    $force_compile

    $caching

    $cache_dir

    $cache_lifetime

    $cache_modified_check

    $php_handling

    $security

    $secure_dir

    $security_settings

    $trusted_dir

    $left_delimiter

    $right_delimiter

    $request_vars_order

    $request_use_auto_globals

    $compile_id

    $use_sub_dirs

    $default_modifiers

    $default_resource_type

    $cache_handler_func

    $autoload_filters

    $config_overwrite

    $config_booleanize

    $config_read_hidden

    $config_fix_newlines

    $default_template_handler_func

    $compiler_file

    $compiler_class

    $config_class

    Handy Built-in Smarty Variables Table

    Built-in Smarty Methods

    assign

    assign_by_ref

    Example: Working of assign and assign_by_ref

    How it Works

    The Result

    append

    append_by_ref

    clear_assign

    register_function

    unregister_function

    register_object

    unregister_object

    register_block

    unregister_block

    register_compiler_function

    unregister_compiler_function

    register_modifier

    unregister_modifier

    register_resource

    unregister_resource

    register_prefilter

    unregister_prefilter

    register_postfilter

    unregister_postfilter

    register_outputfilter

    unregister_outputfilter

    load_filter

    clear_cache

    clear_all_cache

    is_cached

    clear_all_assign

    clear_compiled_tpl

    template_exists

    get_template_vars

    get_config_vars

    trigger_error

    display

    fetch

    config_load

    get_registered_object

    clear_config

    Summary

    9. Caching and Performance

    Caching in Smarty

    Dynamically Caching Template Sections

    Clearing the Cache

    Advanced Caching Features

    Using Cache Groups

    Clearing a Cache Group

    Avoiding the Cache

    Disabling a Template Cache

    Using {insert} to Avoid Caching

    Creating a Custom Plug-in to Avoid Caching on Portions of a Template

    Creating a Custom Cache Handler

    Optimizing Smarty Applications

    Profiling PHP

    Designing Sites for Effective Caching

    The Last-Modified and ETag Headers

    The Expires Header

    The Cache-Control Header

    Tools: ApacheBench (ab)

    Tools: Xdebug

    Tools: WinCacheGrind

    Summary

    10. Extending Smarty with Plug-ins

    Finding and Installing Plug-ins

    Useful Plug-ins

    HTML List Plug-in

    File Size Format Plug-in

    Google Highlight Plug-in

    Writing your own Plug-ins

    Plug-in Types

    Functions

    Modifiers

    Block Functions

    Compiler Functions

    Prefilters, Postfilters, and Output Filters

    Resources

    Inserts

    Registering Plug-ins

    Example Plug-in: Calendar

    Example Plug-in: Auto-link URLs

    Summary

    11. Filters

    Prefilters

    Postfilters

    Output Filters

    Creating Filters

    Registering a Filter at Run Time

    Manually Loading a Filter

    Automatically Loading a Filter

    Filter #1: Remove HTML Comments

    Filter #2: Benchmark Information

    Filter #3: Compress Output with gzip

    Filter #4: Search Engine Highlight

    Summary

    12. Internationalization

    Translation Infrastructure: Gettext

    Configuring PHP with Gettext

    Simple PHP Example

    Setting Up the Gettext Files

    Using Gettext with Smarty

    Generating a PO File

    Advanced Features of Smarty Gettext

    Summary

    Index

    Smarty PHP Template Programming and Applications

    Hasin Hayder

    Joao Prado Maia

    Lucian Gheorghe


    Smarty PHP Template Programming and Applications

    Copyright © 2006 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: April 2006

    Production Reference: 1050406

    Published by Packt Publishing Ltd.

    32 Lincoln Road

    Olton

    Birmingham, B27 6PA, UK.

    ISBN 1-904811-40-X

    www.packtpub.com

    Cover Design by www.visionwt.com

    Credits

    Authors

    João Prado Maia

    Hasin Hayder

    Lucian Gheorghe

    Reviewer

    Mizanur Rahman

    Technical Editor

    Rushabh Sanghavi

    Editorial Manager

    Dipali Chittar

    Development Editor

    David Barnes

    Indexer

    Ashutosh Pande

    Proofreader

    Chris Smith

    Production Coordinator

    Manjiri Nadkarni

    Cover Designer

    Helen Wood

    About the Authors

    João Prado Maia is Lead Software Developer with Alert Logic, Inc. and was previously with MySQL AB as the lead developer behind Eventum, an issue tracking system, and MySQL Network, a subscription product for everything related to MySQL services. He has been working with PHP, Smarty, and PEAR for several years, and maintains phpbrasil.com, one of the most popular PHP-related community sites in Brazil. He is also interested in fostering a community of PHP developers in Houston by organizing the Houston PHP Users Group at http://houstonphp.org.

    I would like to thank my wife for her encouragement and patience while I was writing chapters for this book. I dedicate my work to you, Juliana.

    Hasin Hayder graduated in Civil Engineering from Rajshahi University of Engineering and Technology (RUET). He is an open-source enthusiast who has been programming since early 2001. He maintains phpXperts, the largest PHP user group in Bangladesh, and Zephyr, an open-source AJAX-based MVC framework for PHP5 developers. He is currently working as a web application developer in a Norwegian software development company, Somewhere In.... You can reach him at <[email protected]>.

    I would like to thank my editors from Packt Publishing, David Barnes, Rushabh Sanghavi, and Patricia Weir for this book. Without them I doubt I would have completed my chapters so easily. I would also like to thank Damian and Arnab in Packt Publishing for their help.

    Thanks also go to Mom, Dad, all my family members, Mahbub bhai, Rashidul Hasan and all my friends for supporting me. And finally I would like to thank Ashikuzzaman Fahim and Arild Klokkerhaug, who inspire me a lot.

    I would like to dedicate this book to my wife and my best friend Ayesha. I know I could not live here without you.

    Lucian Gheorghe is currently working as a senior network engineer for Globtel Internet, a significant Internet and Telephony Services Provider to the Romanian market. Even if it’s not his main activity, He has been programming in PHP for over 5 years building billing interfaces, industrial software interfaces, e-commerce sites, and so on. He had a lot of help from a friend called Smarty in his programming experiences.

    Lucian got his first taste of writing when he contributed a few chapters to the book Beginning PHP 5 and MySQL E-Commerce by Cristian Darie and Mihai Bucica, Apress, 2004, with his appendix for Project Management added to the book Beginning ASP.NET 2.0 E-Commerce in C# 2005 by Cristian Darie and Karli Watson, Apress, 2005.

    I would like to thank you for buying this book, my parents for everything they did for me, my girlfriend who stood by me, the team at Globtel, which is like a second family for me and last, but not least a very good friend, the greatest technical author alive—Cristian Darie.

    About the Reviewer

    Mizanur Rahman is a Computer Science graduate from North South University, Bangladesh. He has 7 years of programming experience and vast knowledge on open-source technologies. He has more than 5 years of experience on working with PHP and PHP-related tools and technologies. Currently he is working as a full time senior software engineer in a USA-based software company located in Dhaka.

    Preface

    Smarty is a powerful templating tool that can breathe new life into PHP programming, and solve many of the difficulties PHP programmers face on non-trivial projects.

    This book will take you through the Smarty basics step by step, showing you how to realize the benefits from this product. But this is no hello world tutorial; the book also covers advanced Smarty topics crucial to large-scale web development: performance, internationalization, customization, and so on.

    Smarty is an established engine with a proven track record for making development and design easier and more elegant. Whether you’re just starting with Smarty, or are looking for extra insights on advanced features, this book will help you.

    What This Book Covers

    The first two chapters are an introduction to Smarty. The remaining chapters of the book are divided into two main sections. Chapters 3-7 deal with Smarty template design, and are aimed primarily at designers. The later chapters get more technical, showing how programmers can work with Smarty and PHP to create complex, interactive and high performance applications. Here’s what each chapter covers:

    Chapter 1 will ease you into the world of Smarty. Starting with an overview of what templating systems are and why you use them, it goes on to consider Smarty specifically. Once that’s covered, you’ll see how to install Smarty so you’re ready to begin your Smarty development.

    Chapter 2 discusses how Smarty can make projects easier for programmers and designers, reduce the time taken on programming and maintenance, and bring harmony to the fraught relationship between designers and programmers. You’ll then see how to start your first n-tier Smarty project.

    Chapter 3 is a designer’s overview of Smarty, explaining the key concepts and how designers can create versatile and attractive templates and layouts.

    Chapter 4 looks at templates in detail, showing how values pass into templates and how to use them in applications such as calendars, database-backed reports, email newsletters and more.

    Chapter 5 covers more advanced ways to work with templates, including how to play with variables right in the template using modifiers.

    Chapter 6 delves into the programming side of Smarty. There are many powerful functions that designers can use to make Smarty development easier and more productive. This chapter introduces the most useful of these, and provides practical examples of functions in action.

    With all the added power in the designer’s hands, there are bound to be mistakes occasionally.

    Chapter 7 will introduce you to methods for debugging your Smarty templates, so that you’ll be able to find why the wrong values are being displayed, or that pesky extra tag is ruining your layout.

    Chapter 8 starts with more technical aspects of Smarty. You will see how built-in variables and methods bring added functionality to your PHP code, with very little extra work.

    Chapter 9 looks at how Smarty can make the code itself faster. This in-depth look at Smarty’s caching and performance features, and how to optimize your code for them, will enable you to write very scalable and fast applications with Smarty.

    Chapter 10 pushes Smarty even further, showing how to extend its capabilities with downloadable plug-ins, and even showing how to write your own.

    Chapter 11 takes a detailed look at filters, which are a special kind of plug-in.

    Chapter 12 concludes the book with a look at how to make your website available in different locales and languages using Smarty’s internationalization features.

    Conventions

    In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

    There are three styles for code. Code words in text are shown as follows: We can include other contexts through the use of the include directive.

    A block of code will be set as follows:

    include_once(‘libs/Smarty.class.php’);

    $smarty = new Smarty;

    $smarty->caching = 1;

    $smarty->display(‘example2.tpl’);

    ?>

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold:

    include_once(‘libs/Smarty.class.php’);

    $smarty = new Smarty;

    $smarty->caching = 1;

     

    $smarty->display(‘example2.tpl’);

    ?>

    Any command-line input and output is written as follows:

    $ xgettext -o smartybook.po -n *.php

    New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: clicking the Next button moves you to the next screen.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader Feedback

    Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

    To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

    If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email .

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

    Customer Support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the Example Code for the Book

    Visit http://www.packtpub.com/support, and select this book from the list of titles to download any example code or extra resources for this book. The files available for download will then be displayed.

    Note

    The downloadable files contain instructions on how to use them.

    Errata

    Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata have been verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

    Questions

    You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

    Chapter 1. Introduction to Smarty

    Today, websites are past the level of presenting summary and contact data for companies and projects. With the evolution of the Internet, most websites are now stand-alone businesses rather than summary presentations of companies. More than that, complex applications’ developers have embraced the idea of using websites as interfaces for their software.

    For more than ten years, PHP has been one of the best choices for web developers being the most complete open-source web programming language. With growth of the complexity of PHP applications, a new problem that was raised was, how to separate programmers’ code (PHP) from designers’ code (HTML), or better phrased, how to separate the content from presentation.

    Smarty, a PHP templating system, was born to solve this problem.

    Templating Systems

    The basic functionality of a templating system is introducing a way of separating presentation from content with very little interaction between programmers and designers. For example, the design of a website may look like this:

    Templating Systems

    The designers build the face of the website with pictures, text styles, tables, and so on. They build templates for how to arrange the content in each page.

    The only information the designers need is how the site should look and whether they need to layout content like news, products, jokes, and so on.

    On the other hand, programmers code the application using PHP to do data manipulation (business logic). They are not interested in how the website looks (colors, pictures, text styles) or where the content is laid out on the page. All they need to do is pass the content to the templates using variable names they agree upon with the designers.

    This is roughly how template systems work. Starting from this basic functionality, every template system has a set of features that makes it easier for both designers and programmers if they are well documented in the template system they use.

    This book is intended to show you how to use all the features offered by Smarty in the optimum way.

    Why Use a Templating System?

    Building a website is similar to creating software. It can be done by building it from scratch, just starting to write code to see what you can come up with at the end and solving problems on the way; or it can be done by differentiating the project’s components into separate layers and building the website taking these layers into consideration. This is called multi-tier or multi-level software architecture. If the website is a small one containing only a few lines of PHP code, the first option might work. Just create a few tables in a database, start coding with PHP, maybe create a few banners, generate a few tables and debug every step. People like it this way—fast and easy.

    When it comes to more complicated web-based projects such as web portals, e-commerce sites, ERP systems, and so on, the first option may work but in most cases it can very difficult to achieve anything by coding away. Besides, with the market being so crowded with web projects, in order for your website to stand a chance, you have to have a great layout which is appropriate for the type of project you are building and of course, stable code tested in all situations. That’s why people involved in building websites specialize either in designing great layouts (web designers), or in programming very well (web programmers). Not often will you see a good web programmer creating great designs, or a good web designer writing good, bug-free code.

    A software company that creates websites usually has a design department and a programming department, and most medium to large web projects always have a programmer as well as a designer working on them.

    Programmers have different ways of coding applications and if they use only PHP without a template engine, the designer will need to be familiar with every programmer’s way of arranging the code, naming variables, and so on. Also, the programmer will need to understand the designer’s templates and generate the code to print HTML code from PHP where the designer wants it.

    Let’s take the following example:

    for ( $col = 1; $col < $i; $col++ ) {

      print " $procesid[$col] $data[$col] $value[$col]

    Enjoying the preview?
    Page 1 of 1