Usage of smarty custom functions

Source: Internet
Author: User
Tags echo date naming convention

Preface:
Smarty is not needed for a long time, because most projects are lightweight. Some time ago, I took on a fairly feasible project. Below I have several programmers working with a consortium as the project team. To quickly deploy applications and form a unified view layer control for group members, smarty is selected. It was found that smarty was still so powerful that it was very pornographic and violent.
Author: no Authorization header

Background:
John is a pretty artist MM, and has been working with Jack for many years. Do not misunderstand. If you don't have a head, you have a wife and daughter. They didn't have any relationship before, just colleagues, or superiors and subordinates.
During their years of cooperation, the two have formed a tacit understanding in many places. In many cases, the authorization header provides encapsulated php functions. With some technical modifications, you can directly use John to introduce php functions in the template, in this way, the template can be easily cut into many small pieces for easy maintenance. In addition, because some keywords can be customized, John may quickly retrieve the desired data.
For example:
{Phpsoho "sort = article & order = id desc & limit = 10 & tplfolder = article & tplname = article. list "}


Without a response header, Mr. Zhang provided a user-defined function similar to the preceding one, and clearly provided the usage documents:
Sort: category (article? Download? Image ?) Article | download | picture
Order: sorting method id, hot ,? DESC | ASC
Limit: how many items are Retrieved? Limit number | limit start, end
.......
Of course, not only are these functions defined by phpsoho. John may quickly use the documents she can understand (print) to conveniently perform interface operations.
For various reasons, you are now ready to use SMARTY. Now the question is, how can we make SMARTY support user-defined functions?
Solution:
The SMARTY manual introduces the register_function in this way.

Use this to dynamically register template function plugins. Pass in the template function name, followed by the PHP function name that implements it.
The php-function callback impl can be either (a) a string containing the function name or (B) an array of the form array (& $ object, $ method) with & $ object being a reference to an object and $ method being a string containing the mehod-name or (c) an array of the form array (& $ class, $ method) with $ class being a classname and $ method being a class method of that class.


In fact, I don't know much about so many english. After two days of exploration, I finally had some experiences.

Basics


We can directly use the SMARTY: register_function to register a programmer-defined php function. As long as the file where the function is located has been introduced, we can use it correctly.
DEMO 1:

$ Smarty = set_smarty ();
$ Smarty-> register_function ('example ', 'format _ data ');
$ Smarty-> assign ('time', time ());
$ Smarty-> display('demo.htm ');


The custom functions are as follows:

Function format_data ($ params)
{
Extract ($ params );
Echo date ($ format, $ time );
}


The template file is as follows:

{Example time = "$ time" format = "Y-m-d "}


We can easily deploy and use our custom functions. One thing we need to note is that in the format_data function, we pass in an array pair value. In the template file, we can create any keyword, as long as you can remember. Of course, in addition to the reserved words of SMARTY.
Then we release the values in this array through extract. Of course, there are a variety of such solutions. You can use list or explode, in short, you can think of a good way, as long as you are familiar with it.

Advanced

There was a situation that quickly happened. John was always confused about how many user-defined functions I registered for her to use. She always forgot some keyword definitions, for example, in a hot serialization novel, she does not know whether the keyword "hot" exists. Because there are too many such user-defined functions, she had to take the technical documents I printed for her and look for them with a bitter face. I am very guilty. Therefore, another solution came into being.
At the beginning of this article, I once mentioned "sort = article & order = ID DESC & limit = 10 & tplfolder = article & tplname = article. list "} is an example of such a string in the template. Or you may say that the first brother is deceiving people. This is basically the same as the first example. It is nothing more than a different value. So let's look down...
DEMO 2:
We pretend that the smarty has been instantiated and the resource name is $ smarty.
First, we register a user-defined function to smarty. This is the same as in the example. It is just to cheat a few words.

$ Smarty-> register_function ('phpsoho ', 'tags _ extends ');
// Import the file
Include_once _ ROOT_PATH _. '/include/tags. func. Php ';


Note that the function in the phpsoho handle we registered is tags_extends. What is the meaning of the function name? For details, see the document such as the PHP function naming convention.

Function tags_extends ($ params)
{
$ Action = $ params ['action'];
$ Optional = $ params ['optional'];

/**
* Keyword detection
*/
If (! $ Action)
{
Error: putMsg ('tags _ extends_error ', 'tags _ extends action is null .');
}

If (! Function_exists ($ action ))
{
Error: putMsg ('function _ exists', 'function null. class file. '. $ extend_tags_file.'. classname: '. $ action );
}
$ Action ($ optional );
}


Template File:

{Phpsoho action = "getAffiche" optional = "fileds = id, title, posttime & titlelen = 17 & and [stauts] = 1 & limit = 5 & order = id DESC & tpl = afiche. right "}


The above function execution process is like this:
In the template file, we use the phpsoho resource handle to locate the request to the 'tags _ extends 'function. In this function, we perform several checks:
Check Action: Check whether the action is set. This is a required keyword. In fact, I use this Action to locate the following function.
Check function_exists: Check whether the function to be executed exists or has been loaded
Here we do not need to check optional, because we will perform another check in the next step.
$ Action ($ optional) is executed, that is, getAffiche in the previous example is introduced, and the value of $ optional is set to fileds = id, title, posttime & titlelen = 17 & and [stauts] = 1 & limit = 5 & order = id DESC & tpl = afiche. right, there are some one-to-one ing relationships in it, so I will not explain them too much. I have a document for Xiao Zhang. If you want it, contact her. She's a pretty girl ~!
Looking back, let's look at $ action ($ optional). Why should I look at $ action instead of getAffiche? Who knows what function will you introduce to him in the future? (Smile, smile)
$ Action () DEMO:

Function getAffiche ($ optional)
{
Global $ db;
Parse_str ($ optional );
$ Res = $ db-> getFetchArray ('litou _ affiche ', $ fileds, $ and, $ order, $ limit );

/**
* Declare and send it to the template
*/
$ Smarty = set_smarty ();
$ Smarty-> assign ('titlelen', $ titlelen );
$ Smarty-> assign ('affiche ', $ res );
$ Smarty-> display ($ tpl. $ GLOBALS ['tplex ']);
}


Have you seen this? It turned out to be so simple...
Previously, we completed some operations on the specified content in the function content. Of course, I wrote this article to write this article temporarily, but you can add some advanced php features, such as cache, add cache = 3600 to your character (generally we use seconds, that is, an hour), then you can introduce your cache through some of the above keyword definitions, in addition, you can introduce it after updating based on time, and add filtering or any other functions you want.
In short, everything is possible as long as you have an idea.
Knowledge Point:

Parse_str, Parses the string into variables
Void parse_str (string $ str [, array & $ arr])


This is a very useful function, including parse_ini_file and parse_url, which are used for testing.
Khan: It's almost time to get off work. It's estimated that I can't finish advanced usage today... Let's give a brief introduction, leave a suspense, and edit it later.

Advanced

John is very happy. In this way, she only needs to use this function, and there is not much to remember in it, not a piece of A4 paper. However, I am suffering from this problem. Mr. Zhang often said, "First Brother, I need to take out some picture materials and asked me to arrange four pictures horizontally, eight screenshots in the vertical bar @ $ # ^ % $ % * & ^ * & (), oh, my God, have you done anything wrong? I had to write N more functions for her to use...
Every time I see a little smile, my heart is sweating, alas. No, I want to study it further...

To be continued...
About the Author: No response header. Seven future generations, entering the php family in 03 years. He has participated in the design of the core process of the Beijing court Network case execution system, the core process of the B/S system of Henan Bafang Electric Appliance Co., Ltd., the Shanghai Sunshine Network Association system, and the B/S core system of Shanghai ideal Animation Co., Ltd. development, shanghai Zun Han business Co., Ltd. is now the technical director.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.