PHP imitation blog Park, personal blog (2) _ PHP Tutorial

Source: Internet
Author: User
PHP imitation blog Park, personal blog (2 ). Thank you for your encouragement and support. this is article 2nd. It is also the core of this blog system. After writing this blog, I will put it on my blog website. Here is also my first article. thank you for your encouragement and support. this is article 2nd. It is also the core of this blog system. After writing this blog, I will put it on my blog website. I have a resume here.
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, let's look at my post. class. php. file as our data layer processing class.




This model class inherits a database base class for common operations such as crud. each initialization will initialize a database object $ db. 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 data flow.
There are two more interesting methods, addChildNumber () and reduceChildNumber (), which are used to insert or delete a document. Because my documents can use multiple categories, you must consider the problem when operating the documents. in the category table, a field records the number of documents under this category. Therefore, we need to change these values dynamically.

The following uses the post. php controller to start the data Process. (my controller is not a class, so we cannot generate an API document. Because this is not the true MVC architecture .) Therefore, before MVC, we can better understand whether MVC is a magic horse, and how you apply it and write your own MVC.
The following are all assumptions:
$ Action = "give me a girlfriend in the sky! "; Let's pass in this controller and it will happen.

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 process control statement switch, which is the meaning of the switch. so when the above $ action = "My girlfriend fell to me! "; When a switch is passed in, there are only two possibilities: on and off. This is a bit of double-correlation, and some may see it. Hey!
Let's get down to the truth: Let's see how our switch switches these $ Actions. it's obvious that my girlfriend won't give it to me in the sky, because the controller doesn't have this switch, so we 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 the default switch, so that when there is no girlfriend, we can ensure that we still have friends.
How do I input an action?
Let's look at this url, that is, the navigation of our background framework, post. php? Action = isPost: this is a standard action. each url is actually composed of these actions. you can also add other parameters to our url, in this way, we can GET (GET the value of these variables) in the method defined by the controller, and then we can control more.
Okay, when the url arrives at our controller, we receive the judgment and turn on an isPost switch. in this way, we can call the following method: switch the light and switch the computer, switch is what we often do.
Here we just changed a place.
OK. Let's take a look at the method below this switch.

Function listPost ()
{
$ Results = array ();
$ Results ['pagetitle'] = "Post List ";
$ Results ['path'] = "casual ";
// Set the message
If (isset ($ _ GET ['error'])
{
If ($ _ GET ['error'] = "InsertedFailed") $ results ['errormessage'] = "document addition failed ";
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 is saved to the draft box! ";
}

// Classification of documents
$ Db = MySQL: getInstance ();
$ Pagination = new Pagination;
$ Cat = new Category;
$ Results ['category'] = $ 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 ");
}

}

We have defined an array, $ results = array (); which has obvious functions and will save any data we get from the model, you can also save the GET special parameters from the url. Then it will be displayed in the template contained in require_once (***) below, and the path is defined in the path variable.
At the same time, we will receive two prompt parameters,
Error indicates that an operation error occurs. it is inevitable for anyone, including a computer, to make mistakes. The key is to admit that the computer is doing well and they are brave enough to admit the error.
Status indicates that the operation is successful.
$ Pagination = new Pagination;

This class is our paging class. we pass in a total number for it, and then it will calculate the total number of pages. every time we jump to a page, it is equivalent to refreshing the page, the value of the page on the GET (GET) url in the constructor,
Let us know the current page. At the same time, we re-generate the query statement, followed by a limit statement, similar to limit $ start (start id), $ offset (length); the principle is from this id, give me 10 records later;
My configuration is 10, and you can be more flexible.


$ Cat = new Category;
This class will be detailed later. it is also a very important classification model. Here we will simply get all the categories under this type and display them in the sidebar. I have finished it. There is a picture and a truth!




In this way, all the data required for the page is stored in the $ results array. Okay. let's take a look at how our templates are output.

View Code

1
2
3
4<Br/> 5. blog background management
6
7
8
9
10













11 12 20 21 22 25 37 38 39 65 141 142


13


14 Arist's Blog
15


16


17

Hinging there, everything will be fine.

18


19

23

Operation


24

26

    27
  • Casual

  • 28
  • Article

  • 29
  • Diary

  • 30
  • Comment

  • 31
  • Photo

  • 32

33


34 Current location:
35


36

40


41


    42
  • » Add a new article

  • 43

44


45


46 categories
47


48


49


    50
  • [Edit category]

  • 51
  • [All categories]

  • 52
  • [Unclassified]

  • 53 54 if (isset ($ results ['categories ']) &! Empty ($ results ['category']) {
    55 foreach ($ results ['category'] as $ category ){
    56 echo < 57
  • {$ Category ['name']} ({$ category ['Count _ child_number ']})

  • 58 EOB;
    59}
    60}
    61?>
    62

63


64

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 articles (mainly used for reprinting and publishing original blog posts through "essays ")
77


78


79 80 if (isset ($ results ['posts']) {
81 echo < 82

















Unpublished











83 84 87 91 94 98 101 104 105106 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'] = "publish ";111} else {112 $ post ['status'] ="";113}114 echo <115 116 117 118 119 120 121 122 123 EOB;124}125 echo"

85 title
86

88 release

89 status
90

92 comments
93

Page 95

96 browsing
97

Operation 99
100

102 operations
103
{$ Post ['title']} ({$ time }){$ Post ['status']}{$ Post ['view _ count']}{$ Post ['Comment _ count']}EditDelete
";
126 if (isset ($ pagination) {$ pagination-> createLinks ();}
127} else {
128 echo "no content currently! ";
129}
130
131?>
132
133


134


135
136
137
138
139


140

143


144


145


146


147 Logout
148


149


150


151



152 153 158 159

154


155© Arist
156


157

160
161

All of the above are data.

How can we operate on this data?
Operation is like a control capability. Playing football in the student age, I have a strong ability to control the stadium. I won the championship once in a college football match, once a runner-up, once a runner-up, and I didn't go to my senior year. I have a lot of honors in middle school.
My position is Zhongwei. on the football field, you have to have the ability to view the whole world, strong personal ability, and command ability, now I am sitting in front of the computer every day, and these things have long been gone,
Let's talk about some experience. However, you have to experience it too.

My blog has a disadvantage. every time you perform a read/write operation on the database, you have to refresh it! I know this is a huge load on servers, but I think if you are not completely familiar with a new technology and blindly use it, it will only be counterproductive.
So for the moment, I still sacrifice the server response time and memory consumption to get a relatively stable one!

So I am not very familiar with the global architecture, and there are still many unknown fields not involved, such as in-depth ajax, in-depth php, c... Not much.
Okay. let's see how to perform CRUD on the data!
DELETE
First look at this command post. php? Action = delete & postID = 132
When we confirm that we want to delete this document, we need to first perform a minus 1 operation on the count_child_number field under the category to which the document belongs.
Why? I also started to make a logic error. I only called this method after deletion. remember! ReduceChildNumber () is interesting here, which has benefited me a lot! It also took me a long time to debug!

So: when your syntax is correct, it may be that your logic is wrong! Or the method is incorrect! This is my comment! See:

$ Post = new Post;
$ Filter ['post _ id'] = isset ($ _ GET ['postid'])? (Int) $ _ GET ['postid']: "";

//! Important First reduces the number of articles in this category by 1 before data is deleted.
// Otherwise, you do not know how many articles are deleted under that category.
// I made a logical error. I deleted the document first, and then checked the document's Category ID. I never found the document because it does not exist.
$ Post-> performancechildnumber ("category", (int) $ _ GET ['postid']);

$ Result = $ post-> delete ("post", $ filter );

Here, we only need to initialize the model above the head of our article to easily call the delete () method.

CREATE insert
First look at this command post. php? Action = newPost
To be honest, I haven't inserted it for a long time. Haha! View 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 ['category'] = $ cat-> getCategoryList ("post ");
// Create a 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 it to the 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 at the same time. The key is isset (). when we call the controller's newPost method, we did not import the document to the template.
Therefore, in the template, when we use isset () for judgment, we obtain a null value, which is a good thing. in this way, we will not output any content to the template. In this way, we are waiting for the user to submit the form. here, I am not filtering the form for the sake of convenience, but I leave a backdoor to update it. Okay, let's say that our form has been submitted (and you have basically filtered it out ).

We call storePostFormValues () and storeDiaryFormValues () in the post model. Remember, this method puts all the form content into an array. after checking the basic type,
This is half done. Insert ***(). This is the benefit of the mysql universal database operation class. it can help you process various forms and types. Of course, if you require more details, you can inherit it and expand it.
Or create a method. Here is another step to complete, addChildNumber (). When selecting a category for your document, you also need to add 1 to count_child_number in the corresponding category table.
If you choose to add a document to the draft box, you only need to insert a document record with type = PostDraft.

UPDATE
First look at this command post. php? Action = updatePost & amp; postID = 132
First, you need to obtain the data of this document, postID, which is also obtained by The GET method. In this way, we can initialize the value in the form. Isset () plays a key role here, isn't it?
The following sections are similar: storePostFormValues (), storeDiaryFormValues (); then you call post model update ***().
Check the code:
View Code

Function updatePost ()
{
$ Results ['action'] = "updatePost ";
$ Results ['pagetitle'] = "Edit post ";
$ Post = new Post;
$ Cat = new Category;
$ Results ['category'] = $ 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 ");
}

}



This is almost the case. we have implemented almost all the basic operations.
Some of these actions are navigation, some are generated, and most of them are fixed. Let's use it on your own. Next I will talk about classification! In addition, after this blog is written, it will be placed on a website www.anyui.net.
If you want to learn the source code, I will download it. Thank you for taking this long time to listen to me. I hope you will be happy yesterday.


From warcraft


Bytes. It is also the core of this blog system. After writing this blog, I will put it on my blog website. Here is my one...

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.