Wednesday, March 25, 2009

What is Smarty? Why Smarty? How to use Smarty?

About Smarty [What is, Why/How to Use Smarty]

It’s not a new name when we talk about LAMP. Not even like, I am the first going to write any thing about this.

It’s just for my Quick reference (As many time I collected some good information from the net and later that is not available for so many reason... :) )

Smarty is a PHP template available open source. Easy to use, have good documentation and plug-in available and even allow to write custom fuctions

What is a template and what’s the use to have that?

Templates are used to separate the application logic from presentation logic. Programmer handles the application side and presentation side will be maintained by designer.

So templates try to present the code in such a way so that designer can easily understand or don’t have to go through all the details of coding.

Available PHP templates are:-

  • Smarty PHP template,
  • PEAR::HTML_Template_Flexy PHP template,
  • 4/2/2009 class="MsoNormal" style="">PEAR::HTML_Template_IT PHP template,
  • PEAR::HTML_Template_PHPLIB PHP template,
  • PEAR::HTML_Template_Sigma PHP template,
  • PEAR::HTML_Template_Xipe PHP template,
  • patTemplate PHP template.

Why use Smarty template?

In Smarty’s word:

  • Designers can't break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.
  • Errors in the templates are confined to the Smarty’s error handling routines, making them as simple and intuitive as possible for the designer.
  • With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.
  • Programmers aren't messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.
  • Templates are a close representation of what the final output will be, which an intuitive approach is. Designers don't care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.
  • You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won't breach security, whether intentional or accidental. They can only do what they are confined to in the templates.

Smarty uses {$title} instead of <? echo $title; ?>.

{$title} is less extraneous than <? echo $title; ?>, so it was pretty evident that a simpler syntax helps to make templates easier to read and maintain.

Installation of smarty template

  1. Download smarty. You will get “libs” folder. Libs folder will have : -
    1. internals, plugin, configFile.class.php, debug.tpl, smarty.class.php and smarty_compile.class.php.
  2. Now create four dirs:- (under a folder like /smarty/)
    1. Smarty/templates/
    2. Smarty/template_c/
    3. Smarty/cache/
    4. Smarty/configs/

Note : template_c will have your all compiled template.

  1. Now you will store all your templates in /templates/ folder.
  2. Your config file will be placed at /configs/ folder.
  3. Smarty will store cache file at /cache/ folder, if you have enabled cache. You will enable cache through setting.

Note : Give /template_c and /cache proper permission for writing.

Now start coding with Smarty Template

Your first smarty page: - index.php [PHP file]

// Full path to smarty class-

require ‘your_Smarty_path/Smarty.class.php’;

$smarty = new Smarty();

// Configurations

$smarty->template_dir = ‘your_smarty_path /templates’;

$smarty->compile_dir = ‘your_smarty_path /templates_c’;

$smarty->cache_dir = ‘your_smarty_path /cache’;

$smarty->config_dir = ‘your_smarty_path /configs’;

# now assign variables (defined in template)

$smarty->assign(‘name’, ‘Smarty Enabled File’);

$smarty->display(‘index.tpl’); // template file of index.php

Now index.tpl [Smarty File]

<html>

<head>

<title> My First Smarty File

</head>

<body>

{$name}

</body>

</html>

This is the simplest example of smarty template.

Smarty config file: Smarty config file can have, configuration directives for whole site with some control statement for controlling the config directive usability also. Through this you can tell which variable in config file will be printed or not. The variable can be maintained for section wise also.

Mention config file in template-

{config_load file = ‘config.conf’} at top of the template page.

Use variables of config file like this in template:-

<title> {#pageTitle#}

See two ‘#’ sign before and after variable.

In smarty config file, variable will be declared like this:-

#global variable

pageTitle = 'testing'

You can use double quotes or avoid it in config file. In general use double quotes for string.

Smarty config file can have sections

# student section

[student]

myVars = '…';

# hidden section. Database section.

[.database]

databaseName = 'IGNOU';

databaseUser = 'smarty';

Sample config file

# this is comment

# global vars

pageTitle = 'Testing'

bodyBgColor = 'gray'

[student]

pageTitle = 'Student Info Page'

bodyBgColor = 'orchid'

Use of template variables

{config_load file='config.conf' section='student'}

or

{config_load file='config.conf'}

First will give preference to student section variables in config file. So, when variables in template file do not found in student section then it will look in global variable section.

Documentation for using smarty template

You will find full document of smarty template uses at

Smarty Document

More Smarty Example:

{strip} {/strip} is used in template for stripping whitespace from source.

One dimension array loop in smarty

For Loop

In PHP file:

$arrValue = array('bob','jim','joe','jerry','fred');

$smarty->assign('student', $arrValue);

In Smarty template (tpl) file:

{section name=mysec loop=$student}

{$student[mysec]}

{/section}

Looping Associative array in smarty

In PHP file:

// assign an associative array of data

$arrValue = array(

array('student' => 'bob', 'phone' => '555-3425'),

array('student' => 'jim', 'phone' => '555-4364'),

array('student' => 'joe', 'phone' => '555-3422'),

array('student' => 'jerry', 'phone' => '555-4973'),

array('student' => 'fred', 'phone' => '555-3235')

);

$smarty->assign('student ', $arrValue);

In Smarty Template (tpl) file:

Loop in associative array:

{section name=mysec2 loop=$student }

{strip}

{$users[mysec2].student} : {$users[mysec2].phone}

{/strip}

{/section}

Using PHP code in template (tpl) file:

For running php codes directly in template page, use {php} {/php}.

{php}

echo 'Hello World';

{/php}

Variable modifiers example: capitalize, escape and display date.

In tpl file This will capitalize name variable value:

{$name | capitalize}

Date: {$smarty.nowdate_format:"%d-%m-%Y"}

Include file in template file:

{include file="footer.tpl" title="Header below body"}

Smarty predefined variable

We can use PHP predefined variable in smart template (tpl) file:

Script Name: {$smarty.server.SCRIPT_NAME}

PATH: {$smarty.env.PATH}

PHP_VERSION: {$smarty.const.PHP_VERSION}

Smarty "Capture" Function:

{capture name=banner assign=testAssign}

Hello Testing

{/capture}

Now checking for banner is assigned or not!

{if $smarty.capture.banner ne ''}

{/if}

I have also used assign=testAssign, So I can use this also-

{$testAssign}

Smarty support Custom Function. How to write Custom Function…

Reference :
http://waxjelly.wordpress.com/2007/03/14/how-to-write-a-custom-smarty-function-in-php
http://www.smarty.net

Tuesday, March 24, 2009

How to install MySQL on Windows

Option 1: Use All-in-One distributions packages

There are some distributions packages available that contain Apache, PHP, MySQL and other applications in a single installation file, e.g. XAMPP, WampServer etc.

These packages are good for beginner as well as for Quick setup.

If need custom/ advance configuration use manually installing MySQL, it will help you learn more about the system and give you more control.

Option 2: Manual Installation

Manual Installation

Step 1: Download MySQL

Download MySQL from dev.mysql.com/downloads/. download the “Without installer” version.

Step 2: Extract the files

Extract the ZIP to your C: drive and rename the folder from “mysql-x.x.xx-win32″ to “mysql”.

MySQL can be installed anywhere on your system. If you want a lightweight installation, you can remove every sub-folder except for bin, data, scripts and share.

Step 3: Move the data folder (optional)

I recommend placing the data folder on another drive or partition to make backups and re-installation easier. For the purposes of this example, we will create a folder called D:\MySQLdata and move the contents of C:\mysql\data into it.

You should now have two folders, D:\MySQLdata\mysql and D:\MySQLdata\test. The original C:\mysql\data folder can be removed.

Step 4: Create a configuration file

MySQL provides several configuration methods but, in general, it is easiest to to create a my.ini file in the mysql folder. There are hundreds of options to tweak MySQL to your exact requirements, but the simplest my.ini file is:

[mysqld]

# installation directory

basedir="C:/mysql/"

# data directory

datadir="D:/MySQLdata/"

Step 5: Test your installation

The MySQL server is started by running C:\mysql\bin\mysqld.exe. Open a command box (Start > Run > cmd) and enter the following commands:

cd \mysql\bin

mysqld

This will start the MySQL server which listens for requests on localhost port 3306. You can now start the MySQL command line tool and connect to the database.

Open another command box and enter:

cd \mysql\bin

mysql -u root

This will show a welcome message and the mysql> prompt. Enter “show databases;” to view a list of the pre-defined databases.

Step 6: change the root password

The MySQL root user is an all-powerful account that can create and destroy databases. If you are on a shared network, it is advisable to change the default (blank) password. From the mysql> prompt, enter:

UPDATE mysql.user SET password=PASSWORD("my-new-password") WHERE User='root';

FLUSH PRIVILEGES;

You will be prompted for the password the next time you start the MySQL command line.

Enter “exit” at the mysql> prompt to stop the command line client. You should now shut down MySQL with the following command:

mysqladmin.exe -u root shutdown

Step 7: Install MySQL as a Windows service

From a command prompt, enter:

cd \mysql\bin

mysqld --install

Open the Control Panel, Administrative Tools, and then Services and double-click MySQL.

Set the Startup type to “Automatic” to ensure MySQL starts every time you boot your PC.

Alternatively, set the Startup type to “Manual” and launch MySQL whenever you choose using the command “net start mysql”.

The Windows service can be removed using:

cd \mysql\bin

mysqld --remove

Friday, September 26, 2008

Configure PHP to Send fax

Like to configure your PHP to send fax :

Need a working installation of the following:

* HylaFAX 4.4 or HylaFAX EE 3
* PHP 5
* PHP PEAR 5 including MDB2_driver_mysql, Mail and Mail_Mime
* PECL FileInfo
* PHP mbstring - for improved UTF-8 sorting support (optional)
* PHP MySQL 5
* MySQL server 4.1.12 or better (see Important Notes below)
* Apache
* ImageMagick
* ghostscript
* libtiff
* netpbm-progs
* libungif
* sudo
* sendmail/postfix/exim/qmail or use an external SMTP server
* cups/lpr and psutils
* expect

Follow the installation instruction from below link.

Refrence : http://www.avantfax.com/install.php
http://www.hylafax.org/


HylaFAX is designed to be very robust and reliable. The fax server is designed to guard against unexpected failures in the software, in the configuration, in the hardware and in general use. HylaFAX can support multiple modems and a heavy traffic load.

HylaFAX supports:

* sending facsimile
* receiving facsimile
* polled retrieval of facsimile
* transparent shared data use of the modem
* sending alpha-numeric pages
Hylafax can be use to send SMS.

Wednesday, September 24, 2008

Installing SMTP serve on Linux

install an SMTP serve

sudo apt-get install postfix

Want to change configuration settings :

sudo dpkg-reconfigure postfix


Reference : http://my.opera.com/Contrid/blog/show.dml/478684

Wednesday, September 3, 2008

Common PHP design patterns

Design patterns were introduced to the software community in Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the "gang of four").

The core concept behind design patterns, presented in the introduction, was simple.

Using design patterns in PHP code is one way to make code more readable and maintainable. By using established patterns, We benefit from common design constructs that allow other developers on a team to understand our code's purpose. It also allows us to benefit from the work done by other designers, so we don't have to learn the hard lessons of design ideas that don't work out.

Common patterns for PHP.

The factory pattern
The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.

sometimes such patterns can seem like overkill in small situations.

The singleton pattern
Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it's an overhead to keep opening and closing connections, particularly during a single page fetch.

The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time.

The observer pattern
The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn't relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.

This pattern isn't limited to objects in memory. It's the underpinning of the database-driven message queuing systems used in larger applications.

The chain-of-command pattern

Building on the loose-coupling theme, the chain-of-command pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers.

The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.

The strategy pattern

In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts -- one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.

The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.

The adapter pattern

Use the adapter pattern when you need to convert an object of one type to an object of another type. The adapter pattern is a nice way to clean this type of code up and reuse all your assignment code in other places. Also, it hides the assignment code, which can simplify things quite a bit if you're also doing some formatting along the way.

The iterator pattern

The iterator pattern provides a way to encapsulate looping through a collection or array of objects. It is particularly handy if you want to loop through different types of objects in the collection.

The decorator pattern

The delegate pattern
The delegate pattern provides a way of delegating behavior based on different criteria.

The state pattern