Create the simplest PHP development mode in the World 1th/5 page _php Basics

Source: Internet
Author: User
Tags wrapper
/*************************************/
/* Author: older Youth
/* email:wenadmin@sina.com
/* From:http://blog.csdn.net/hahawen
/*************************************/

PHP as the "simplest" Web scripting language, in the domestic market is more and more big, phper more and more, but feel that most people don't seem to take into account the mode of the problem, what kind of design mode is the best, is the most suitable for their current work, after all, efficiency is the most important (save time to play games, how beautiful AH ... )。 MVC should be the first choice, and there are a lot of excellent open source projects based on MVC on the www.sourceforge.net, so you can go over the research.

A few days ago to their own company website revision, mainly or article release system, the boss said backstage I want how to design how to design, the only premise is fast. So I built a simple framework for the release system. If simply from the article release system, basically can meet the "small and medium-sized" Enterprise website article publishing system requirements, the total background of PHP code not more than 800 lines, and support arbitrary expansion and plugin function.

No more nonsense, I would like to talk about the framework below, I hope you can help.

Note: Before you begin, 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

To start with the distribution of files throughout the Web site, the following sections will be followed by creating and populating these directories and files
The root directory of my server's Web is "c:/apache2/htdocs/"
I set up a folder "Cmstest" as the home folder for my site below.
The sub-file structure under folder "Cmstest" 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 Smarttemplate's class library.
/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 own company's website and the structure of the template you have designed, summarize the features you want to implement, and list the list.
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 according to the function
Design a profile config.inc.php to record some basic information about the site, including the database name ...
The interface function of database query is designed for each kind of function, so the similar operation should call this interface once. This avoids the possibility of a lot of code duplication in the future, and it achieves the purpose of code reuse.
Define your own wrapper function on the template tool, and then call the template tool without the use of the problem, only to their own packaging function inside the number of plug it.
The underlying function is OK, starting with easy page implementation and template processing.

We are now starting to design a simple system to see how I can achieve a "simplest article of the publishing system" step-by-step, of course, just a simple project I simulate, in fact, a project may be more complex than this.


First, analysis of my case:

Oh, this customer project is very simple ah, happy ing ...

List1.php: There are three articles list and a button, "PHP Development article List" "PHP Development Hot Article List" "ASP Development Latest article" "Add new article"
List2.php: 2 articles List "ASP Development articles List" "ASP Development hotspot articles List"
new.php: A page that adds a form to an article
add.php: A page that handles new.php's forms
view.php: The page that the article inspects

Second, analysis function

"PHP Development Articles List" "ASP Development article List"-------by the Order of the article published, in reverse sequence display, each page shows 5 articles
"PHP Development Hot Article List" "ASP Development Hot Article List"-------by the number of clicks to see the article sorted display article, display 3 article
"ASP development of the latest article" according to the published order of the article, the reverse display, display 3 article
"Add new article"------The publishing feature of an article, including article title/author/content
"Article View"---------show the content of an article

In a comprehensive look, the functional categories include:
1, the article list: The normal pagination list, by the number of clicks List, by the list of publish order
2, Article release: a form of input and processing
3, article view: Read the contents of the display article

Oh, the function is really too simple some.

Third, the design of the database:

Database name: cmstest

Data table:

CREATE TABLE ' article ' (
' ID ' INT not NULL auto_increment,
' title ' VARCHAR 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 not NULL,
PRIMARY KEY (' CID ')
);

------------------------------
The article table is the content table of the article,
----------------------------
' ID ' article number
' title ' article title
' Content ' article contents
' DateTime ' release time
' clicks ' Number of clicks
' PID ' category table number
------------------------------
Cat table is a category table for articles
----------------------------
' CID ' classified form #
' CNAME ' category name
----------------------------

Above is the database structure of the table, the light has not enough, but also have 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 1:1:1", 0, 1);
INSERT into ' article ' VALUES (2, "PHP Development 2", "PHP Development 2 Content", "2004-8-2 1:1:1", 0, 1);
INSERT into ' article ' VALUES (3, "PHP Development 3", "PHP Development 3 content", "2004-8-3 1:1:1", 4, 1);
INSERT into ' article ' VALUES (4, "PHP Development 4", "PHP Development 4 Content", "2004-8-4 1:1:1", 3, 1);
INSERT into ' article ' VALUES (5, "PHP Development 5", "PHP Development 5 content", "2004-8-5 1:1:1", 2, 1);
INSERT into ' article ' VALUES (6, "PHP Development 6", "PHP Development 6 content", "2004-8-6 1:1:1", 1, 1);
INSERT into ' article ' VALUES (7, "PHP Development 7", "PHP Development 7 Content", "2004-8-7 1:1:1", 0, 1);
INSERT into ' article ' VALUES (8, "JSP Development 1", "JSP Development 1 Content", "2004-8-1 1:1:1", 0, 2);
INSERT into ' article ' VALUES (9, "JSP Development 2", "JSP Development 2 Content", "2004-8-2 1:1:1", 0, 2);
INSERT into ' article ' VALUES (Ten, "JSP development 3", "JSP development 3 Content", "2004-8-3 1:1:1", 4, 2);
INSERT into ' article ' VALUES (one, "JSP development 4", "JSP development 4 Content", "2004-8-4 1:1:1", 3, 2);
INSERT into ' article ' VALUES ("JSP Development 5", "JSP development 5 content", "2004-8-5 1:1:1", 2, 2);
INSERT into ' article ' VALUES ("JSP Development 6", "JSP development 6 Content", "2004-8-6 1:1:1", 1, 2);
INSERT into ' article ' VALUES ("JSP Development 7", "JSP development 7 Content", "2004-8-7 1:1:1", 0, 2);


So our database is finished. Then comes the concrete implementation.

Iv. Design of config.inc.php documents

This file is used to set up some common web data information and some parameters, the other specific implementation page to get the required data, the following is the configuration of the list

<?php

Database Settings
Define (' Db_username ', ' root ');
Define (' Db_password ', ');
Define (' db_host ', ' localhost ');
Define (' db_name ', ' cmstest ');
Define (' Db_pconnect ', true);

The basic path of the web is set
Define (' Cms_root ', ' c:/apache2/htdocs/cmstest/');
Define (' Cms_srcpath ', cms_root. ' src/');

Settings for the Smarttemplate Template resolution tool
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 ');

The underlying files to include, which are 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 ();

?>


One of the define (' Cms_root ', ' c:/apache2/htdocs/cmstest/'); The road is changed according to its own Apach Web path (refer to the place where the folder structure was first introduced).


Five, the Production function interface (1)

First of all, the MySQL database function packaging to simplify the operation of the database, online there are many such open source classes. But here I personally according to their own needs and habits, the MySQL function of the packaging, write the good or bad first. This is a simple place to look at the different types of packaging operations are different, and the main purpose here is to understand this set of "architecture", do not have to buckle 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? (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 [' islast '] = $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) {
$t 1 = $t 2 = array ();
foreach ($data as $key => $value) {
$t 1[] = $key;
$t 2[] = "'". Addslashes ($value). "'";
}
Return ' INSERT into $table ('. Implode (",", $t 1). ") VALUES (". Implode (", ", $t 2).") ";
}

function Sqlmakeupdatebyid ($table, $field, $id, $data) {
$t 1 = array ();
foreach ($data as $key => $value) {
$t 1[] = "$key = '". Addslashes ($value). "'";
}
Return "UPDATE $table SET". Implode (",", $t 1). " WHERE $field = $id ";
}

function Sqlmakedelbyid ($table, $field, $id) {
Return ' DELETE from $table WHERE $field = $id ';
}

?>

Five, the Production function interface (2)

Here's a formal look, we're going to implement the functionality of the wrapper

------------articleutil.php----------------
<?php
function to display a list of articles
Getarticlelist (article category, sorting method, currently showing the first few pages, each page shows several)
function Getarticlelist ($catId, $order, $page, $pageSize) {
$sql = "SELECT * from article WHERE pid= $catId Order by $order";
Return Dbpagequery ($sql, $page, $pageSize);
}
Querying the contents 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 (article content Array)
function Addarticle ($data) {
$sql = Sqlmakeinsert (' article ', $data);
Return Dbexecute ($sql);
}
?>

Is this code a lot simpler? This is your own MySQL function to the benefits of packaging!
Here's a look at how they can achieve our function.
"PHP Development article List"--------Getarticlelist (1, "id DESC", $page, 5)
"ASP Development Articles List"--------Getarticlelist (2, "id DESC", $page, 5)
"PHP Development Hotspot Articles List"----getarticlelist (1, "clicks DESC, ID DESC", 1, 3)
"ASP Development hotspot Articles 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 article"---------------getarticle ($id)


Vi. Packaging for Smarttemplate (revolution not yet successful, comrades still have to work hard)

The use of specific smarttemplate here will not speak, or Spit said no, can not finish. The following is a specific pair of wrapper functions

-------------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 ();
}

?>
Current 1/5 page 12345 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.