Home > Backend Development > PHP Tutorial > PHP imitation blog park, personal blog (2)_PHP tutorial

PHP imitation blog park, personal blog (2)_PHP tutorial

WBOY
Release: 2016-07-13 17:51:41
Original
1376 people have browsed it

Thank you in advance for your encouragement and support. This is the second article. It is also the core thing of this blog system. After writing this blog, I will put it on my blog site. There is also a resume of mine here.
Without further ado, the core concept in the previous article is give action do something!
In this article, I will use code to explain what this concept means. First, look at my post.class.php. This file is our data layer processing class.




Let me briefly introduce this model class. It inherits a database base class to perform common operations such as crud. Each time it is initialized, a database object $db will be initialized. We use this object to operate our data.
There are two important methods for data operations: storePostFormValues() and storeDiaryFormValues(). These two methods are the beginning of the data flow.
There are two other interesting methods, addChildNumber( ) and reduceChildNumber( ), which are responsible for a black-box operation when inserting or deleting documents. Because my document can be classified into multiple categories, one issue I need to consider when operating the document is that there is a field in the category table that records the number of documents under this category. So the values ​​of these numbers need to be changed dynamically.

Next, with the post.php controller, we can start the process of our data (my controller is not yet a class, so the API document cannot be generated. Because this is not a real MVC architecture.) So before MVC, this is also It will be more conducive to understand what MVC is, and how you can apply it and write your own MVC.
The following situations are all assumptions:
$action = "Give me a girlfriend from the sky!"; Let's pass in this controller and see what happens.

require_once( "config/config.php" );
session_start( );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
$username = isset( $_SESSION['username'] ) ? $_SESSION['username'] : "";

if( !$username )
{
header("Location: index.php?action=login");
exit;
}

Here we have an important flow control statement switch, which means switch; so when the above $action = "Give me a girlfriend from the sky!"; when switch is passed in, there are only two possibilities, one is On, one is off. There is a bit of a pun here, and some students may see it. hey-hey!
Closer to home: look at how our switch turns these $actions on and off. It’s obvious that I won’t get a girlfriend from the sky, because there is no such switch in the controller, so I can only talk about the code.

switch( $action )
{
case "newPost" :
newPost( );
Break;
 
case "delete" :
         delete( ) ;
Break;
 
case "updatePost":
         updatePost( );
Break;
 
case "IsDraft":
listDraft( );
Break;
 
case "logout" :
Logout( );
Break;
 
case "isPost":
listPost( );
Break;
 
case "diffentCategoryPost":
        diffentCategoryPost( );
Break;
 
case "unCategory":
         unCategory( );
Break;
 
default:
listPost( );
Break;
}


Each switch should define a default switch, so that when we don't have a girlfriend, we can ensure that we still have gay friends.
How to pass in action?
Let’s look at such a URL, which is the navigation of our background framework. Post.php?action=isPost This is a standard action. Each of our URLs is actually composed of these actions. You can also add other parameters to it. in our url, so that we can GET (get the values ​​of these variables) in the methods defined in the controller, and then we can have more control.
Okay, when this url reaches our controller, we receive the judgment and then turn on an isPost switch so that we can call the following methods. Think about turning on and off lights and computers. Switches are what we often do. .
Here we just changed the place.
OK. Let’s look at the following method for this switch.

function listPost( )
{
$results = array( );
$results['pageTitle'] = "Post List" ;
$results['path'] = "Essay";
// set the message
If ( isset( $_GET['error'] ) )
{
If ( $_GET['error'] == "InsertedFailed" ) $results['errorMessage'] = "Failed to add document";
If ( $_GET['error'] == "postDeleteFailed" ) $results['errorMessage'] = "Document deletion failed";
}
If ( isset( $_GET['status'] ) )
{
If ( $_GET['status'] == "changesSaved" ) $results['statusMessage'] = "The document is saved!";
If ( $_GET['status'] == "Deleted" ) $results['statusMessage'] = "The document has been deleted!";
If ( $_GET['status'] == "Inserted" ) $results['statusMessage'] = "You added a new document!";
If ( $_GET['status'] == "SaveToDraft" ) $results['statusMessage'] = "The document was saved to the draft box!";
}
 
// Browse documents by category
$db = MySQL::getInstance( );
    $pagination = new Pagination;
    $cat = new Category;
    $results['categories'] =  $cat->getCategoryList("post");
   
    $pagination->countSQL = "select * from post where type = 'post' " ;
    $db->Query( $pagination->countSQL );
    $pagination->totalRecords = $db->RowCount( );
    $records = $db->HasRecords( $pagination->rebuiltSQL( ) );
    if( $records )
    {
        $results['posts'] = $db->QueryArray( $pagination->rebuiltSQL( ) );
        require_once(TEMPLATE_PATH . "/post/post_list.php");
    }
    else
    {
        require_once(TEMPLATE_PATH . "/post/post_list.php");
    }
   
 }
 

我们定义了一个数组,$results = array( ); 这个数组的作用明显,它将保存我们从 model 中获取的任何数据,也可以保存从url上 GET 的特殊参数。然后将在我们下面require_once(*****) 包含的模版中显示出来, 路径定义在了 path 变量中。
同时我们会接收2个提示参数,
error , 表示操作出现错误,任何人都在所难免,包括电脑,谁都会犯错,关键是去承认,电脑做的很好,他们勇于承认错误。
status; 表示状态,就是成功的操作。
$pagination = new Pagination;

这个类是我们的分页类,我们传入一个 总的数量给它,然后它自己会算出总页数,每跳转一个页面,相当于刷新了一次,所以大家的做法就是,在构造器里 GET(获取)url上的page 的值,
让我们知道是当前那一页了。同时我们重新生成了查询的语句,后面加上一条限制的语句,类似 limit $start(起始的id), $offset(长度); 原理就是从这个id起,往后给我10 条记录;
我的设定就是 10 条,你也可以更灵活。


$cat = new Category;
这个类后面会详细说,也是非常重要的分类model。这里我们就是简单获取 这个类型下的所有分类,显示在侧边栏,我已经完成了。有图有真相!
PHP imitation blog park, personal blog (2)_PHP tutorial



 

这样 我们的 $results 数组中就储存了我们页面所需的所有数据。 好的,来看看我们的模版,是怎么输出的。
 
  View Code
 
  1
  2
  3    


  4         <br>   5             博客后台管理
  6            
  7                       
  8        
  9    
 10            
 11                
 12                    
 20                
 21                
 22                    
 25                    
 37                
 38                
 39                    
 65                    
141                
142            

 23                        
操作

 24                    

 66                        

 67                

 68                
 69                  70                     if( isset( $results['statusMessage'] )){echo  $results['statusMessage'];}
 71                     if( isset( $results['errorMessage'] )){echo  $results['errorMessage'];}
 72                 ?>
 73                

 74

 75    

 76         文章(主要用于转载,发布原创博文要通过“随笔”)
 77    

 78    
    
 79  80     if( isset( $results['posts'] )){
 81     echo  82            
 83                
 84                    
 87                    
 91                    
 94                                  
 98                    
101                    
104                
105        
106 EOB;
107         foreach( $results['posts'] as $post ){
108             $time = date("Y-m-d H:i:s", $post['create_time']);
109             if( $post['status'] == "1" ){
110                 $post['status']  = "发布";
111             }    else {
112                 $post['status']  = "未发布";
113             }
114             echo 115            
116                
117                
118                
119                
120                
121                    
122            
123 EOB;
124         }
125             echo "

 85                         标题
 86                    

 88                         发布

 89                         状态
 90                    

 92                         评论
 93                    

 95                         页面

 96                         浏览
 97                    

 99                         操作
100                    

102                         操作
103                    
{$post['title']} ({$time}) {$post['status']} {$post['view_count']} {$post['comment_count']} 编辑 删除
";               
126             if( isset( $pagination) ){$pagination->createLinks( ) ;}
127     } else {
128         echo "当前无内容!";
129     }
130
131 ?>  
132
133    

134

135
136
137
138
139                        

140                    

143            

144                
146                
         
147                    logout
148                

149                

150            

151            
152                
153                    
160
161

The above is just to show the data, everyone can do it.

How do we operate on this data?
Operation is like a control ability. When I was playing football as a student, I had a strong ability to control the court. I won one championship, one runner-up, and one third place in college football games. I didn't go to senior year, and I also won numerous honors in middle school.
My position is central defender. In this position on the football field, you must have the ability to see the overall situation, strong personal ability, and commanding ability. To put it a step further, now you sit in front of the computer every day. The stuff is gone a long time ago,
Just some words of experience remain. But you must also experience the taste.

There is a shortcoming of my blog. Every time you perform a read or write operation on the database, you have to refresh it! I know this places a heavy load on the server, but I feel that if you don’t fully understand a new technology and use it blindly, it will only be counterproductive.
So for the time being, I still sacrifice the server's response time and memory consumption to achieve relative stability!

So I don't know the overall situation very well, and there are still many unknown areas that I haven't gotten involved in, such as going deep into Ajax, going deep into PHP, and C. . . No more to say.
Okay, let’s see how to CRUD data!
DELETE Delete
First look at this command post.php?action=delete&postID=132
When we confirm that we want to delete, there is something to note here. We can first perform a subtraction operation of 1 on the count_child_number field under the category to which the document belongs.
Why? Because I also started to make a logical mistake, I only called this method after deletion, remember! The interesting part of reduceChildNumber() is here, and it has benefited me a lot! It also took me a long time to debug!

So: when your grammar is correct, your logic may be wrong! Or the method is wrong! That's my note! Please see:

​$post = new Post;
$filter['post_id'] = isset( $_GET['postID'] ) ? ( int )$_GET['postID'] : "";
 
// !important Before deleting data, reduce the number of articles in this category by 1
// Otherwise you don’t know the number of articles to delete in that category
// I made a logical mistake. I deleted the document first, and then checked the category ID of the document; I could never find it because it no longer existed.
$post->reduceChildNumber( "category", ( int ) $_GET['postID'] );
 
$result = $post->delete("post", $filter );

Here we can easily call the delete() method as long as we initialize the model at the top of our article.

CREATE INSERT
Let’s look at this command first: post.php?action=newPost
To be honest, I haven't inserted it in a long time. hehe! See the control method:
View Code

function newPost( )
{
$results['action'] = "newPost" ;
$results['pageTitle'] = "Add New post" ;
$results['newPost'] = "true";
$results['path'] = "Essay» Add Essay" ;
$post = new Post;
$cat = new Category;
$results['categories'] = $cat->getCategoryList( "post");
//Create new document
If( isset( $_POST['saveChanged'] ))

$post-> storePostFormValues( $_POST );
$result = $post->insertPost( );
          if( $result )
           {
                 $post->addChildNumber( "category", $_POST['category'] );
header("Location: post.php?action=isPost&status=Inserted");
}
        else
           {
header("Location: post.php?action=isPost&error=InsertedFailed");
}
                // Save to draft box
} else if( isset( $_POST['saveDraft']) )
{
          $post = new Post;
$post-> storePostFormValues( $_POST );
$post->saveDraft( );
header("Location: post.php?action=isPost&status=postSaveToDraft");
               // cancel
} else if( isset( $_POST['cancel'] ))
{
header("Location: post.php?action=isPost");
}
else
{
         require_once(TEMPLATE_PATH . "/post/post_edit.php");
}
}


We use a template to insert and update documents simultaneously. The key is isset(). When we call the newPost method of the controller, we do not pass the document into the template.
So in the template, when we use isset() to make a judgment, we get a null value, which is a good thing; in this way, we will not output anything to the template. In this way, we wait for the user to submit the form. Here, to save trouble, I have not filtered the form for the time being, but I have left a backdoor to update it later. Okay, let's say our form is submitted (and filtered by your basic filter).

We call storePostFormValues( ) and storeDiaryFormValues( ) in the post model; remember, this method puts all the form contents into an array. After doing basic type checking,
This is already half the battle. Below is insert***(). This is the benefit of mysql's universal database operation class, which can help you handle various forms and types. Of course, if you have more detailed requirements, you can inherit it and extend it
its method, or a new method. There is still one step to complete here, addChildNumber(). When you select a category for your document, you also add 1 to the count_child_number in the corresponding category table.
If the user chooses to put the document into the draft box, just insert a document record with type = PostDraft.

UPDATE
First look at this command post.php?action=updatePost&postID=132
To update, you must first obtain the data of this document, postID, which is also obtained by the GET method. This way we can initialize the value in the form. isset() plays a key role here, doesn't it?
The following parts are similar, storePostFormValues(), storeDiaryFormValues(); and then you call post model update***().
Look at the code:
View Code

function updatePost( )
{
$results['action'] = "updatePost";
$results['pageTitle'] = "Edit post";
$post = new Post;
$cat = new Category;
$results['categories'] = $cat->getCategoryList("post");
If( isset( $_POST['saveChanged'] ))
{
               // do update
$post->storePostFormValues( $_POST );
$post->updatePost( );
header("Location: post.php?action=isPost&status=changesSaved") ; } else if( isset( $_POST['cancel'] ) )
{
header("Location: post.php?action=isPost&status=Cancel");
}else
{
             // get the post                                                     $postID = isset( $_GET['postID'] ) ? $_GET['postID'] : " ";
          $results['post'] = $post->getPostByID( $postID );
         require_once(TEMPLATE_PATH . "/post/post_edit.php");
}
 
}



That's it almost here, we have implemented almost all the basic operations.
A few notes: some of these actions are navigation, some are generated, and most of them are fixed. Use it yourself. The next article talks about classification! Also, after this blog is written, it will be posted on a website www.anyui.net
If you want to learn from the source code, I will provide it for download. Thank you for spending so long listening to my chatter. For those who see this sentence, I wish you a happy 6.1 yesterday, hehe.

Excerpted from warcraft



http://www.bkjia.com/PHPjc/478182.html

truehttp: //www.bkjia.com/PHPjc/478182.htmlTechArticleThank you in advance for your encouragement and support. This is the second article. It is also the core thing of this blog system. After writing this blog, I will put it on my blog site. Here is one of mine too...
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