Smarty class 1th/3 page _php tips for new handwritten combinations

Source: Internet
Author: User
Tags dsn error handling

Specifically for the new handwritten combination of Smarty class, sincerely invite you to give more valuable advice


This is for beginners (also for themselves) to write the combination of Smarty class, is not completed, now put out the purpose is not immediately let novice use, so also did not write the notes very detailed
I hope you master a lot of advice, I try to perfect it.
First of all, I wrote this for the purpose of exercising myself, although I know that there are many similar classes now, but I decided to write a
So please let us have a good time while browsing.

There are also files I have been packaged uploaded, put in the following, please download a lot, many suggestions. What's the problem directly Q I

Currently, the class includes the following features (use the example, set $m = new Machine_m ())
Database
Currently supports MySQL and access two kinds of databases
Configure Reference config.php files
Use: $m->send_query (SQL statement)//
$m->select_query (SQL statement, whether to return a resource, default to False is to return a two-dimensional array)

[Error Handling]
Divided into system errors and user errors
System error:
$this->sys_err (' Configuration error, please check config profile ', ' die ');
The first parameter logs the error message to/lib/error/system.err, the second parameter is the processing method (keep or Die), and if you need to modify the browser-side prompts, you can set a third parameter, which defaults to "Sorry, there is a system error on this site, please try again later." ”
User error:
$m->user_err (' Registration system shutdown ', ' die ', $_server[' http_referer ']);
The first parameter is the prompt to display to the browser end, the second parameter is the processing method (keep or Die), the third parameter is the jump page, and if you need to log the error message, you can also set the fourth parameter, which will log the error message
To/lib/error/user.err, do not set default without saving.

The browser-side error prompts the default call to the err_page.htm template file under/lib/error/, or you can set up your own error template file, and then load it with $m->err_page=.

[Static generation]
Static pages are automatically generated in just one line, and static page expiration time can be set when jumping
(now still incomplete static, completely more complex, there is no integration at present, if you want to achieve complete static, you can combine my create_html function and text operation series function implementation)
How to use:
$m->create_html (template file, static output path, output filename);
Jump:
$m->goto_html ();
The output filename is equal to the file name of the current PHP file, provided this parameter is intended to be used when static paging is required, which is used to set the

[Two-dimensional array ordering (recommended)]
You can make a two-dimensional array look like this: "First by field a, then by field B in descending order"
How to use:
An array is provided: $x = Array (' name ' => ' Machine_ ', ' age ' =>23), Array (' name ' => ' Tom ', age=>28),......)
Now we're going to sort this array by name in ascending order, and then by age descending
The usage is m_sort ($x, ' name ', Sort_asc, ' age ', Sort_desc)

[Dynamic loading]
For less commonly used functions, I use the method of loading, I think this can save resources
For example, if we want to use the M_sort function, the default is not to load the function
Need to load like this: $m->load_func (' M_sort ')
And then you can use the M_sort function.

[Paging]
Here I do not know how to do well, I wrote a class first, and then write a function to tune it, the purpose is to use the time is more convenient
Usage: m_page (number of data bars, current page number, how many rows per page, how many jump links are displayed)
function returns an array of: Array (
' Rows ' => how many rows per page to display,
' Prve ' => on a large page number,//So-called Big page, is similar to 7 pages, the next 7 pages such a jump
' Next ' => the next big page number,
How many pages of ' pages ' => are there,
' Start ' => the number of starting records for SQL queries,
How many records are there in the ' count ' =>,
' Links ' => link page number,//If there are 13 pages, the number of links is 7, and is currently on the second largest page, output array (8,9,10,11,12,13)
' Current_page ' => current page number
);

[Validate the form]
The need to verify the form in advance into the function class, discriminant when only need to pass the $_post to the
How to use: This is a function you should see, this function needs to be modified according to their own needs

[Prevent cross-site attacks]
This function is also written in a function.

[Chinese intercept function]
I didn't write it.

[Upload file]
M_up_file ($_files, upload path, file type, size limit)
Where the upload path can be set, 1: Directly write folder path, 2:array (' gif ' => ' file/gif ', ' jpg ' => ' file=>jpg '), so that GIF files automatically put into the File/gif folder, JPG files into the File/jpg folder
File type: Writing 1: ' jpg ', writing 2:array (' jpg ', ' jpeg ', ' gif ')
Returns array (' arr ' => uploaded file arrays, ' err_msg ' => error message during upload, ' num ' => upload success number)

[Text operation (recommended)]
Suppose there is such a string $str = "Hello <!--content-->phpchina<!--/content-->";
We can modify $new _str=m_txt_replace (' content ', ' Machine_ horse ', $str).
Now the value of $new_str is "Hello <!--content-->machine_ Horse <!--/content-->"
Several other functions, such as: M_txt_add,m_txt_delete,m_txt_get, are similar and can be seen by yourselves.

Note: This is the method of modifying the static page after it is generated.
You can see 6TO23 and think about why he put so many replies in a post so fast
A: Because its replies did not go into the database but directly to the static file inside, and then use the method similar to my above to modify. You can look at his source code, look for <!--you know.


Now the basic implementation is the above features
And then I'm going to do

[Picture Processing]
[UBB Code Output]

And some other common functions

I hope you master a lot of advice
Main class:

Copy Code code as follows:


<?php
Session_cache_limiter (' private,must-revalidate ');
Session_Start ();

if (!defined (' This_dir '))
{
Die (' System error: path constant lost ');
}
if (@!include_once (This_dir). ' lib/smarty/smarty.class.php '))
{
Die (' System error: Smarty file missing ');
}

Unset ($GLOBALS);
unset ($HTTP _cookie_vars);
unset ($HTTP _env_vars);
unset ($HTTP _get_vars);
unset ($HTTP _post_files);
unset ($HTTP _post_vars);
unset ($HTTP _server_vars);
unset ($HTTP _session_vars);

Class Machine_m extends Smarty
{
Database Resources
Private $conn;
Path
Private $the _dir;
Configuration file
Private $config = Array ();
Private $config _url;
List of external functions
Private $func _list = Array ();
Private $func _list_url;
Error Prompt page
Public $err _page = ' lib/error/err_page.htm ';
Static generation
Public $html _cache = ' html ';
Public $html _cache_lifetime = 86400;

Constructors
Public function __construct ($test = False)
{
Preserve the Smarty class's construction section
$this->assign (' Script_name ', isset ($_server[' script_name ')? $_server[' Script_name ']
: @ $GLOBALS [' http_server_vars '] [' script_name ']);

Now it's the machine_m part of the building.
$this->left_delimiter = ' <% ';
$this->right_delimiter = '%> ';
$this->the_dir = This_dir;
$this->config_url = "{$this->the_dir}lib/config/config.php";
$this->config = $this->parse_ini ();
$this->func_list_url = "{$this->the_dir}lib/config/func_list.php";
$this->func_list = $this->parse_func ();
$this->state ($test);
$this->load_func (Array (' m_addslashes ', ' m_stripslashes '));
$this->connect ();
}

destructor
Public Function __destruct ()
{
}

Set Web Site Status functions
Private function State ($test)
{
if ($test = = True)
{
$this->load_func (Array (' M_print_r ', ' m_var_dump '));
$this->compile_check = true;
Error_reporting (E_all);
}
Else
{
$this->compile_check = false;
error_reporting (0);
}
}

Resolving profile functions
Private Function Parse_ini ()
{
if (!file_exists ($this->config_url))
{
$this->sys_err ("Config profile missing", ' die ');
}
$config = Parse_ini_file ($this->config_url);
if (!array_key_exists (' host_name ', $config)
|| !array_key_exists (' user_name ', $config)
|| !array_key_exists (' db_name ', $config)
|| !array_key_exists (' password ', $config))
{
$this->sys_err (' Configuration error, please check config profile ', ' die ');
}
$config = $this->decode_config ($config);
Settype ($config, ' object ');
return $config;
}

Analytic function List function
Private Function Parse_func ()
{
if (!file_exists ($this->func_list_url))
{
$this->sys_err ("func_list configuration file Missing", ' die ');
}
$func _list = parse_ini_file ($this->func_list_url);
return $func _list;
}

External function Load function
Public Function Load_func ($FUNC)
{
if (Is_array ($func))
{
foreach ($func as $func _name)
{
$this->include_file ($this->func_list[$func _name]);
}
}
Else
{
$this->include_file ($this->func_list[$func]);
}
}

External functions include functions
Public Function Include_file ($file _url)
{
$file _url = $this->the_dir. $file _url;
@ $ok = include_once ($file _url);
if ($ok!= true)
{
$this->sys_err ("file {{$file _url}} Failed to load", ' die ');
}
}

The config file decoding function (the database username and password plaintext record is not safe, preferably first encrypted, and then decrypted here, this function can be overloaded)
protected function Decode_config ($config)
{
return $config;
}

Connect database functions
Private Function Connect ()
{
Switch (Strtoupper ($this->config->database))
{
Case ' MYSQL ':
$this->connect_mysql ();
Break
Case ' ACCESS ':
$this->connect_access ();
Break
Default:
$this->sys_err (' Database type error, this class currently only supports MySQL and access two kinds of databases ', ' die ');
Break
}
}

connecting MySQL database functions
Private Function Connect_mysql ()
{
if ($this->conn!= null)
{
@mysql_close ($this->conn);
$this->conn = null;
}
@ $this->conn = mysql_connect ($this->config->host_name, $this->config->user_name, $this->config- >password);
if ($this->conn = = False)
{
$mysql _err = Mysql_error ();
$this->sys_err ("MySQL database connection failed because: {{$mysql _err}}", ' die ');
}
@ $db = mysql_select_db ($this->config->db_name, $this->conn);
if ($db = = False)
{
$mysql _err = Mysql_error ();
$this->sys_err ("Data table connection failed because: {{$mysql _err}}", ' die ');
}
}

Connect Access database functions
Private Function Connect_access ()
{
if ($this->conn!= null)
{
@odbc_close ($this->conn);
$this->conn = null;
}
$dsn = ' Driver=microsoft Access Driver (*.mdb);d bq= '. Realpath ($this->the_dir. $this->config->db_name);
@ $this->conn = Odbc_connect ($dsn, $this->config->user_name, $this->config->password);
if ($this->conn = = False)
{
@ $odbc _err = odbc_errormsg ($this->conn);
$this->sys_err ("Access database connection failed because: {{$odbc _err}}", ' die ');
}
}
Current 1/3 page 123 Next read the full text

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.