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 I don't talk much about one of my resumes. 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.
The code is as follows:
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.
The code is as follows:
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.
The code is as follows:
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 calculates the total number of pages. every time a page is redirected, it is equivalent to refreshing it once, so everyone's practice is to GET the page value on the GET (GET) url in the constructor and let us know that it is 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, I will give you 10 records in the future. I set 10 records, and you can also 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.
The code is as follows:
<BR> blog background management
Arist's Blog
Hinging there, everything will be fine.
|
Operation |
- Casual
- Article
- Diary
- Comment
- Photo
Current location:
|
Category
- [Edit category]
- [All categories]
- [Unclassified]
If (isset ($ results ['categories ']) &! Empty ($ results ['category']) {
Foreach ($ results ['category'] as $ category ){
Echo <
- {$ Category ['name']} ({$ category ['Count _ child_number ']})
EOB;
}
}
?>
|
If (isset ($ results ['statusmessage']) {echo $ results ['statusmessage'];} If (isset ($ results ['errormessage']) {echo $ results ['errormessage'];} ?>
Article (mainly used for reprinting and publishing original blog posts through "essays ")
If (isset ($ results ['posts']) { Echo <
Unpublished
Title |
Release
Status |
Comment |
Page
Browse |
Operation |
Operation |
EOB;Foreach ($ results ['posts'] as $ post ){$ Time = date ("Y-m-d H: I: s", $ post ['create _ time']);If ($ post ['status'] = "1 "){$ Post ['status'] = "publish ";} Else {$ Post ['status'] ="";}Echo <
{$ Post ['title']} ({$ time }) |
{$ Post ['status']} |
{$ Post ['view _ count']} |
{$ Post ['Comment _ count']} |
Edit |
Delete |
EOB;}Echo"
"; If (isset ($ pagination) {$ pagination-> createLinks ();} } Else { Echo "no content currently! "; }
?>
|
Logout
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 should first perform a minus 1 operation on the count_child_number field under the category to which this document belongs.
Why? I also started to make a logical 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:
The code is as follows:
$ 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:
The code is as follows:
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:
The code is as follows:
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! This blog will be placed on a website after it is written.
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.