Creating the world's simplest PHP development model Page 1/5_PHP Tutorial

WBOY
Release: 2016-07-21 15:59:35
Original
938 people have browsed it

/*************************************/
/* author: older youth
/* email: wenadmin@sina.com
/* from: http://blog.csdn.net/hahawen
/*************************************/

 php, as the “simplest” Web scripting language, is getting bigger and bigger in the domestic market, and there are more and more phpers, but it feels like most people don’t think about the model. The question is, what kind of design pattern is optimal and most suitable for your current work? After all, efficiency is the most important (playing games with the saved time, how beautiful...). MVC should be the first choice. There are many excellent open source projects based on MVC on www.sourceforge.net. You can rush there to study them.

A few days ago, I revamped my company website, mainly the article publishing system. My boss said that I can design the backend however I want. The only prerequisite is that it be fast. So I built a simple publishing system framework. If we look purely at the article publishing system, it can basically meet the requirements of the article publishing system for "small and medium-sized" enterprise websites. The total PHP code in the background does not exceed 800 lines, and it supports arbitrary expansion and plugin functions.

No more nonsense, let me talk about my structure below, I hope it will be helpful to you.

Note: Before starting, you need to download a template processing tool class: "smarttemplate" and understand 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 in the entire web site. In the following chapters, we will create and fill in the following Directories and files
The root directory of my server’s web is “C:/Apache2/htdocs/”
I created a folder “cmstest” below as the main folder of my website
The sub-file structure under the 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 the smarttemplate 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 company’s website and the structure of the designed template, summarize the functions to be implemented, and make a list.
Analyze the function list and classify the functions. Each type of function has something in common and can be implemented through the same method.
Design the table structure of the database according to the function
Design a configuration file config.inc.php to record some basic information of the website, including the database name...
For each One type of function is to design the interface function for database query, so that similar operations in the future only need to call this interface. This avoids a large number of code duplication operations that may occur in the future, and achieves the purpose of code reuse.
Define your own packaging function for the template tool. When you call it in the future, you don’t have to worry about the use of the template tool. You only need to stuff it into your own packaging function.
The basic functions are now ok, let’s start easy page implementation and template processing.

We will now start to design a simple system to see how I implemented a "simplest article publishing system" step by step. Of course, it is just a simple project that I simulated. In reality, one Projects can be more complex than this.


1. Analysis of my case:

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

list1.php: There are three article lists and one button, "php development article list" "php development hot article list" "asp development latest article" "add new article"
list2.php: there are 2 article lists "asp "Development article list" "ASP development hot article list"
new.php: A page for adding an article form
add.php: A page for processing the new.php form
view.php: Article viewing Page

2. Analysis function

"php development article list" "asp development article list" ------- display in reverse order according to the publication order of the articles, with 5 displayed on each page Articles
"php development hot article list" "asp development hot article list" ------- Display articles sorted by the number of clicks and views of the article, showing 3 articles
"asp development latest article" button The publishing order of articles is displayed in reverse order, showing 3 articles
"Add new article" ------ The publishing function of an article, including article title/author/content
"View article" --- ------Display the content of an article

Take a comprehensive look and classify the functions including:
1. Article list: normal paging list, list by clicks, and order of publication List
2. Article publishing: input and processing of a form
3. Article viewing: reading and displaying article content

Haha, the function is indeed too simple.

3. Design database:

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` )
);

---------------- ----------------
article table is the article content table,
----------------------- -----
`id` Article number
`title` Article title
`content` Article content
`datetime` Release time
`clicks` Number of clicks
`pid `Category table number
-----------------------------
The cat table is the category table of the article
----------------------------
`cid` Classification table number
`cname` Classification name
-- --------------------------

The above is the database structure of the table. It is not enough to have these alone, you also need 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(10, "jsp development 3", "jsp development 3 content", "2004-8-3 1:1:1 ", 4, 2);
INSERT INTO `article` VALUES(11, "jsp development 4", "jsp development 4 content", "2004-8-4 1:1:1", 3, 2);
INSERT INTO `article` VALUES(12, "jsp development 5", "jsp development 5 content", "2004-8-5 1:1:1", 2, 2);
INSERT INTO `article ` VALUES(13, "jsp development 6", "jsp development 6 content", "2004-8-6 1:1:1", 1, 2);
INSERT INTO `article` VALUES(14, "jsp Development 7", "jsp development 7 content", "2004-8-7 1:1:1", 0, 2);


In this way, our database is designed. Next comes the specific implementation.

4. Design the config.inc.php file

This file is used to set some common data information and some parameters on the web. Other specific implementation pages are obtained through this page. Data, the following is a list of configurations


//Database settings
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'cmstest');
define('DB_PCONNECT', true);

// Basic path settings for web
define('CMS_ROOT', 'C:/Apache2/htdocs/cmstest/');
define('CMS_SRCPATH', CMS_ROOT.'src/');

//Smarttemplate template parsing tool settings
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); lib/smarttemplate/class.smarttemplate.php');

//The basic files to be included contain 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();

?>


                                 


  Wherein define('CMS_ROOT', 'C:/Apache2/htdocs/cmstest/'); The path is based on Change the web path of apach yourself (refer to the place where the folder structure was first introduced).


5. Making functional interfaces (1) First, wrap the mysql database function to simplify database operations. There are many such open source classes on the Internet. But here I personally package the mysql function based on my own needs and habits, and I don’t care whether it is good or bad. Just take a quick look at this place. The class operations of different packages are different, and the main purpose here is to understand this "architecture" without being too tight on the code.

-------MysqlUtil.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('数据库连接错误'); 
    mysql_select_db(DB_NAME, $cnn) or die('数据库选择错误'); 
    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语句执行错误'); 
    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['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语句执行错误'); 
    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)."'";                    WHERE $field=$id";
}

function sqlMakeDelById($table, $field, $id){
return "DELETE FROM $table WHERE $field=$id";
} 

?>

5. Making functional interfaces (2)

Let’s take a formal look at the packaging of the functions we want to implement

------------ArticleUtil.php----------------
//Display the article list Function
//getArticleList(article category, sorting method, which page is currently displayed, how many articles are displayed on each 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 article
//addArticle (article content array)
function addArticle($data){
$sql = sqlMakeInsert('article', $data);
return dbExecute($sql);
}
?>

Is this code much simpler? This is the benefit of wrapping the mysql function yourself!
Let’s 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 hot article list"----getArticleList(1, "clicks DESC, id DESC", 1, 3)
"asp development hot article List"----getArticleList(2, "clicks DESC, id DESC", 1, 3)
"ASP development latest articles"----getArticleList(2, "id DESC", 1, 3)
"Add new article"-------------addArticle($data)
"View article"-------------------------- getArticle($id)


6. Packaging the smarttemplate class (the revolution has not yet succeeded, comrades still have to work hard)

I won’t go into the specific use of smarttemplate here, otherwise it will be boring. I won’t be able to finish talking if I run out of words. The following is a specific wrapper 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); > $page->output();
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317380.htmlTechArticle/*************************************/ /*author:Older Youth/*email:wenadmin@sina.com / *from:http://blog.csdn.net/hahawen /*************************************/ php as "the simplest...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!