Create the world's simplest PHP development model page 1/5

Source: Internet
Author: User
Tags mysql functions

/*************************************/
/* Author: young adults
/* Email: wenadmin@sina.com
/* From: http://blog.csdn.net/hahawen
/*************************************/

As the "simplest" Web scripting language, php is growing in the domestic market and phper is growing. However, it seems that most people have not considered the pattern problem and what kind of design pattern is the best, is the most suitable for your current work, after all, efficiency is the most important (using the time to play games, how beautiful ...). MVC should be the first choice. There are many excellent MVC-based Open Source Projects on www.sourceforge.net, so you can skip the research.

I revised my company's website a few days ago, mainly through the article publishing system. The boss said that I would like to design the website in the background, but the only premise is fast. So I built a simple release system framework. From the perspective of the article publishing system, it can basically meet the requirements of the article publishing system for "small and medium-sized" Enterprise websites. The total number of php code lines in the background should not exceed 800, it also supports arbitrary expansion and plugin functions.

I will not talk about it anymore. Let's talk about my architecture and hope it will help you.

Note: Before starting, You need to download a template processing tool class: "smarttemplate" and learn about the simple use of some templates.

My test environment: windows2k/apache2/php4.3.2/smarttemplate class library

First, let's talk about the distribution of files on the entire web site. In the subsequent sections, we will create and fill in the following directories and files.
The web root directory of my server is "C:/Apache2/htdocs /"
I created a folder "cmstest" below as the main folder of my website
The sub-file structure under the "cmstest" folder is:

/Config. inc. php
/List1.php
/List2.php
/New. php
/Add. php
/View. php
/Page. js
/Src/MysqlUtil. php
/Src/ArticleUtil. php
/Src/CoreUtil. php
/Src/ParseTpl. php
/Src/lib/smarttemplate/*. * This directory is used to store
/Smart/template/list1.htm
/Smart/template/list2.htm
/Smart/template/new.htm
/Smart/template/add.htm
/Smart/template/view.htm
/Smart/cache/
/Smart/temp/


Design steps:

Consider the characteristics of your company's website and the structure of the designed template, summarize the functions to be implemented, and list them.
Analyze the function list and classify the functions. Each type of function has something in common and can be implemented in the same way.
Design the table structure of the database based on the Function
Design a configuration file config. inc. php to record some basic information about the website, including the database name ........
Design database query interface functions for each type of function, so that similar operations can be called in the future. This avoids a large number of code repetitive operations in the future, and achieves the purpose of code reuse.
Define your own packaging function for the template tool. You don't need to worry about the use of the template tool when calling it later. You only need to add a number to your own packaging function.
The basic function is okay, so you can easily implement the page and process the template.

Now let's start designing a simple system to see how I can implement a "simplest article publishing system" step by step. Of course, it's just a simple project I have simulated, in reality, a project may be much more complicated than this.


I. analyze my cases:

Haha, this customer project is so simple, happy ing ..........

List1.php: contains a list of three articles and a button, "php development article list", "php development hotspot article list", "asp development latest article", and "Add new Article"
List2.php: List of two articles: "asp development article list" and "asp development hotspot article list"
New. php: a page for adding an article form
Add. php: page for processing new. php forms
View. php: page viewed by the article

Ii. analysis functions

"Php development article list" "asp development article list" ------- displays articles in reverse order in the order they are published. Five articles are displayed on each page.
"Php development hotspot article list" "asp development hotspot article list" ------- sort by the number of clicks to view the article and display 3 articles
"Asp development latest articles" are displayed in reverse order according to the Publishing order of the articles. Three articles are displayed.
"Add new article" ------ the publishing function of an article, including the article title/author/Content
"View articles" --------- display the content of an article

After a comprehensive look, the functions are classified as follows:
1. Article list: normal paging list, by-click list, and by-order list
2. Article publishing: input and processing of a form
3. view the article: Read and display the article content

The features are indeed too simple.

Iii. Database Design:

Database Name: cmstest

Data Table:

Create table 'Article '(
'Id' int not null AUTO_INCREMENT,
'Title' VARCHAR (100) not null,
'Content' text not null,
'Datetime' datetime not null,
'Clicks' INT (11 ),
'Pid 'TINYINT (2) not null,
Primary key ('id ')
);

Create table 'cat '(
'Cid' TINYINT (2) not null,
'Cname' VARCHAR (20) not null,
Primary key ('cid ')
);

------------------------------
The article table is the document content table,
----------------------------
'Id' Document No.
'Title' article title
'Content' content
'Datetime' release time
'Clicks' clicks
'Pid' category table number
------------------------------
Cat table is the document category table.
----------------------------
'Cid' Category Table No.
'Cname' category name
----------------------------

The above is the database structure of the table. It is not enough to have enough data.
Insert into 'cat' VALUES (1, "php development"), (2, "asp development ");
Insert into 'Article' VALUES (1, "php development 1", "php development 1 content", "2004-8-1", 0, 1 );
Insert into 'Article' VALUES (2, "php development 2", "php development 2 content", "2004-8-2", 0, 1 );
Insert into 'Article' VALUES (3, "php development 3", "php development 3 content", "2004-8-3", 4, 1 );
Insert into 'Article' VALUES (4, "php development 4", "php development 4 content", "2004-8-4", 3, 1 );
Insert into 'Article' VALUES (5, "php development 5", "php development 5 content", "2004-8-5", 2, 1 );
Insert into 'Article' VALUES (6, "php development 6", "php development 6 content", "2004-8-6", 1, 1 );
Insert into 'Article' VALUES (7, "php development 7", "php development 7 content", "2004-8-7", 0, 1 );
Insert into 'Article' VALUES (8, "jsp development 1", "jsp development 1 content", "2004-8-1", 0, 2 );
Insert into 'Article' VALUES (9, "jsp development 2", "jsp development 2 content", "2004-8-2", 0, 2 );
Insert into 'Article' VALUES (10, "jsp development 3", "jsp development 3 content", "2004-8-3", 4, 2 );
Insert into 'Article' VALUES (11, "jsp development 4", "jsp development 4 content", "2004-8-4", 3, 2 );
Insert into 'Article' VALUES (12, "jsp development 5", "jsp development 5 content", "2004-8-5", 2, 2 );
Insert into 'Article' VALUES (13, "jsp development 6", "jsp development 6 content", "2004-8-6", 1, 2 );
Insert into 'Article' VALUES (14, "jsp development 7", "jsp development 7 content", "2004-8-7", 0, 2 );


In this way, our database is completely designed. The specific implementation is involved.

4. design the config. inc. php file

This file is used to set some common web data information and some parameters. Other specific implementation pages use this page to obtain the required data. below is the configuration list.

<? Php

// Database settings
Define ('db _ username', 'root ');
Define ('db _ password ','');
Define ('db _ host', 'localhost ');
Define ('db _ name', 'cmstest ');
Define ('db _ PCONNECT ', true );

// Set the basic web path
Define ('cms _ root', 'c:/Apache2/htdocs/cmstest /');
Define ('cms _ SRCPATH ', CMS_ROOT. 'src /');

// Settings of the template parsing tool for smarttemplate
Define ('smart _ REUSE_CODE ', false );
Define ('smart _ TEMPLATE_DIR ', CMS_ROOT. 'Smart/template /');
Define ('smart _ TEMP_DIR ', CMS_ROOT. 'Smart/temp /');
Define ('smart _ CACHE_DIR ', CMS_ROOT. 'Smart/cache /');
Define ('smart _ cache_lifetime', 100 );
Require_once (CMS_SRCPATH. 'lib/smarttemplate/class. smarttemplate. php ');

// Basic file to be included, which contains some basic functions
Require_once CMS_SRCPATH. 'mysqlutil. php ';
Require_once CMS_SRCPATH. 'articleutil. php ';
Require_once CMS_SRCPATH. 'coreutil. php ';
Require_once CMS_SRCPATH. 'parsetpl. php ';

// Session control
Session_cache_limiter ('private _ no_expire ');
Session_start ();

?>


Define ('cms _ root', 'c:/Apache2/htdocs/cmstest /'); the road Sutra is changed based on your own apach web road Sutra (refer to the local change to introduce the folder structure at the beginning ).


5. create functional interfaces (1)

First, we pack mysql database functions to simplify database operations. There are many such open-source classes on the Internet. But here I personally wrap mysql functions according to my own needs and habits. If I write well, I will ignore it first. You can simply take a look at this place. Different packaging class operations are different, and the main purpose here is to understand this set of "architecture", so there is no need to buckle the code.

------- MysqlUtil. php --------
<? Php

Function dbConnect (){
Global $ cnn;
$ Cnn = (DB_PCONNECT? Mysql_pconnect (DB_HOST, DB_NAME, DB_PASSWORD ):
Mysql_connect (DB_HOST, DB_NAME, DB_PASSWORD) or
Die ('database connection error ');
Mysql_select_db (DB_NAME, $ cnn) or die ('database selection error ');
Mysql_query ("set autocommit = 1 ");
}

Function & dbQuery ($ SQL ){
Global $ cnn;
$ Rs = & mysql_query ($ SQL, $ cnn );
While ($ item = mysql_fetch_assoc ($ rs )){
$ Data [] = $ item;
}
Return $ data;
}

Function & dbGetRow ($ SQL ){
Global $ cnn;
$ Rs = mysql_query ($ SQL) or die ('SQL statement execution error ');
If (mysql_num_rows ($ rs)> 0)
Return mysql_fetch_assoc ($ rs );
Else
Return null;
}

Function dbGetOne ($ SQL, $ fildName ){
$ Rs = dbGetRow ($ SQL );
Return sizeof ($ rs) = null? Null: (isset ($ rs [$ fildName])? $ Rs [$ fildName]: null );
}

Function & dbPageQuery ($ SQL, $ page = 1, $ pageSize = 20 ){
If ($ page = null) return dbQuery ($ SQL );
$ CountSql = preg_replace ('| SELECT. * FROM | I', 'select COUNT (*) count from', $ SQL );
$ N = (int) dbGetOne ($ countSql, 'Count ');
$ Data ['pagesize'] = (int) $ pageSize <1? 20: (int) $ pageSize;
$ Data ['recordcount'] = $ n;
$ Data ['pagecount'] = ceil ($ data ['recordcount']/$ data ['pagesize']);
$ Data ['page'] = $ data ['pagecount'] = 0? 0: (int) $ page <1? 1: (int) $ page );
$ Data ['page'] = $ data ['page']> $ data ['pagecount']? $ Data ['pagecount']: $ data ['page'];
$ Data ['isfirst'] = $ data ['page']> 1? False: true;
$ Data ['isla'] = $ data ['page'] <$ data ['pagecount']? False: true;
$ Data ['start'] = ($ data ['page'] = 0 )? 0: ($ data ['page']-1) * $ data ['pagesize'] + 1;
$ Data ['end'] = ($ data ['start'] + $ data ['pagesize']-1 );
$ Data ['end'] = $ data ['end']> $ data ['recordcount']? $ Data ['recordcount']: $ data ['end'];
$ Data ['SQL'] = $ SQL. 'limit'. ($ data ['start']-1). ','. $ data ['pagesize'];
$ Data ['data'] = & dbQuery ($ data ['SQL']);
Return $ data;
}

Function dbExecute ($ SQL ){
Global $ cnn;
Mysql_query ($ SQL, $ cnn) or die ('SQL statement execution error ');
Return mysql_affected_rows ($ cnn );
}

Function dbDisconnect (){
Global $ cnn;
Mysql_close ($ cnn );
}

Function sqlGetOneById ($ table, $ field, $ id ){
Return "SELECT * FROM $ table WHERE $ field = $ id ";
}

Function sqlMakeInsert ($ table, $ data ){
$ T1 = $ t2 = array ();
Foreach ($ data as $ key => $ value ){
$ T1 [] = $ key;
$ T2 [] = "'". addslashes ($ value )."'";
}
Return "insert into $ table (". implode (",", $ t1). ") VALUES (". implode (",", $ t2 ).")";
}

Function sqlMakeUpdateById ($ table, $ field, $ id, $ data ){
$ T1 = array ();
Foreach ($ data as $ key => $ value ){
$ T1 [] = "$ key = '". addslashes ($ value )."'";
}
Return "UPDATE $ table SET". implode (",", $ t1). "WHERE $ field = $ id ";
}

Function sqlMakeDelById ($ table, $ field, $ id ){
Return "delete from $ table WHERE $ field = $ id ";
}

?>

5. create functional interfaces (2)

Next let's take a formal look at the packaging of the functions we want to implement.

------------ ArticleUtil. php ----------------
<? Php
// Function for displaying the document list
// GetArticleList (document category, sorting method, number of pages currently displayed, and number of entries per page)
Function getArticleList ($ catId, $ order, $ page, $ pageSize ){
$ SQL = "SELECT * FROM article WHERE pid = $ catId ORDER BY $ order ";
Return dbPageQuery ($ SQL, $ page, $ pageSize );
}
// Query the content of an article
// GetArticle (article number)
Function getArticle ($ id ){
$ SqlUpdate = "UPDATE article SET clicks = clicks + 1 WHERE id = $ id ";
DbExecute ($ sqlUpdate );
$ SQL = "SELECT * FROM article WHERE art_id = $ id ";
Return dbGetRow ($ SQL );
}
// Add an article
// AddArticle (array of article content)
Function addArticle ($ data ){
$ SQL = sqlMakeInsert ('Article', $ data );
Return dbExecute ($ SQL );
}
?>

Is this code much simpler? This is the benefit of packing mysql functions!
Next we will study how they implement our functions.
"Php development article list" -------- getArticleList (1, "id DESC", $ page, 5)
"Asp development article list" -------- getArticleList (2, "id DESC", $ page, 5)
"Php development hotspot article list" ---- getArticleList (1, "clicks DESC, id DESC", 1, 3)
"Asp hot article list" ---- getArticleList (2, "clicks DESC, id DESC", 1, 3)
"Asp development latest article" -------- getArticleList (2, "id DESC", 1, 3)
"Add new article" ------------- addArticle ($ data)
"View articles" --------------- getArticle ($ id)


6. Package the smarttemplate class (the revolution has not yet succeeded, and comrades still need to work hard)

The usage of the specific smarttemplate will not be discussed here, or the saliva will not be enough. The following is a specific packaging function.

------------- ParseTpl. php ----------------
<? Php

Function renderTpl ($ viewFile, $ data ){
$ Page = new SmartTemplate ($ viewFile );
Foreach ($ data as $ key => $ value ){
If (isset ($ value [data]) {
$ Page-> assign ($ key, $ value [data]);
Unset ($ value [data]);
$ Page-> assign ($ key. "_ page", $ value );
} Else {
$ Page-> assign ($ key, $ value );
}
}
$ Page-> output ();
}

?>

Related Article

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.