Start your MVC (3) with PHP to achieve your Model layer

zhaozj2021-02-12  162

Third, realize your MODE layer

The MODEL layer is the data processing layer in the MVC mode, which is used to design the data and business logic, design to three concepts:

------ MODEL class. It is a physical class. Data used to save all the fields of the record of the database table. And you can verify this integrity of the recorded data.

------ ModelManager class. Is the management class of the entity class. Usually, each entity class (model) has a corresponding management class (ModelManager). The management class can be used to manage data records in the entity class (for example, delete / add / change .....). But the ModelManager class does not have to have a corresponding Model class.

------ DB class. Used to manage the connection to the database. ModeElManager class all the operations of data. It is achieved by this DB class. In the entire MVC mode. Only this DB class can operate directly. At the same time, only the ModelManager class can call the DB class.

It seems that it is more troublesome. But actually is not complicated. This model layer design is designed. The shopping cart program for online shopping systems is extremely similar. Model can be seen as the information class of a single commodity in the shopping cart. Manager can be regarded as an order. Orders are used to manage procurement products.

Here is a simple example. It should be relatively typical. Focus on his entire design and process. Take carefully. In fact, it is not difficult.

Note: All classes and methods used in the following examples are simplified. The actual situation is much more complicated than this. but. As an example, it is already enough.

Folder structure:

| - DB.PHP | - MODEL.PHP | - MANAGER.PHP | - MODELTEST1.PHP | - MODELTEST2.PHP | - MODELTEST3.PHP | - MODELTEST4.PHP | - MODELTEST4.PHP | - MODEL / | - MODEL / CLASSMODEL.PHP | - MODEL / StudentModel.php | - MODEL / CLASSMANAGER.PHP | - MODEL / StudentManager.php Note the case of folders and file names

Content: Suppose there is a database, saved in two tables, one is a class form, one is a table of Student (student),

Class Table Field: CLS_ID --------- INT -------- NOT NULL CLS_NAME -------- String ----- Not null cls_address ----- String ----- Nullstudent Table field: stu_id --------- INT -------- Not Null Stu_clsid ------- Int -------- Not null STU_NAME -------- String ----- NULL

ClassModel.php entity class which is a table inside ClassModelClassManager.php class management class ClassModel ClassManagerStudentModel.php entity class which is a table inside StudentModelStudentManager.php student management class StudentManagerDb.php StudentModel which is a database management class operation His interface and normal usage are the same, but this example is only analog implementation of this excuse. Therefore, you can run without a real database.

File 0: (Model.php) MODEL layer entity base class

1, "name" => "this is name"); var $ data; // This entity class data constraint information, used to determine the accuracy of the added $ DATA data // see: ClassModel Var $ match; // The name of the table in the database in the database VAR $ TABLE; / / Initializing Function Model ($ THIS-> DATA = & $ data;} // Setting the entity for a value Function Set ($ key, $ value) {$ this-> data [$ key ] = $ Value;} // Get a data of this entity Function Get ($ key) {Return $ this-> data [$ key];} // Get all the data for this entity Function getData () {Return $ this -> data;} // Get the constraint information of the entity Function getMatch () {Return $ this-> match;} // Verify the accuracy of the entity data and integrity Function isvalid () {foreach ($ this-> match as $ key => $ value) {if (! isset ($ value ["null"]) &&! isset ($ this-> data [$ key]) DIE ("$ key can not be empty"); / / ..... Can be added to other judgments, such as exceeding the maximum number of values, or long long .....}}}?> File 1: (manager.php) MODEL layer is based on entity management class

db = new db ();} // Used Insert entity information into the database Function INSERT ($ model) {$ model-> isvalid (); $ table = $ model-> table; $ match = $ model-> getMatch (); $ data = $ model-> getData (); $ Str1 = $ str2 = array (); foreach ($ match as $ key => $ value) {ix ($ data ($ data [$ key)) {$ str1 [] = $ key; $ str2 [ ] = ($ Value ["type"] == "c")? "/"""" ": $ data [$ key];}} $ sql =" INSERT INTO $ Table (". IMPLODE (", ", $ str2).") ""). ")"; return $ this-> db-> execute ($ sql);}} ?> File 2: (ClassModel.php) Class of Class Information

Array ("name" => "cls_id", "type" => "i"), "cls_name" => array ("name" => "CLS_NAME", "TYPE "=>" C ")," CLS_ADDRESS "=> Array (" Name "=>" CLS_ADDRESS "," type "=>" c "," null "=> true)); var $ TABLE =" Class "; // Initialize Function ClassModel (& $ DATA) {Parent :: Model ($ data);} // Used to get this class of students' information function getStudent () {require_once "./model/studentmanager.php"; $ manager = New StudentManager (); $ classid = $ this-> get ("cls_id"); return $ manager-> getList ($ classid);}}?> File 3: (studEntModel.php) physical information

array ("name" => "stu_id", "type" => "i"), "stu_clsid" => array ("name" => "stu_clsid", "TYPE "=>" I ")," stu_name "=> Array (" name "=>" stu_name "," type "=>" c "," null "=> true); var $ table =" student "; // Initialize Function StudentModel (& $ DATA) {Parent :: Model ($ data);}}?> File 4: (Classmanager.php) class entity management class

db-> query ($ SQL);} // Find and return a class entity class Function & FindOndOndel ($ ID) {$ SQL =" SELECT * FORM CLASS WHERE CLS_ID = ID "; $ Data = $ this-> DB-> getone ($ data == null) Die ("The class does not exist!"); Require_once "./model/classmodel.php"; $ model = new classmodel ($ data); return $ model;}}?>

File 5: (studentManager.php) student entity management class

db-> query ($ sql);}}?> file 6: (db.php) database connection management class for sharing and manage Data Access. Since the content involved in this class is not the content to be discussed, this class simulates "Method of Real Database Management Class", the excuse is the same, but the content inside the interface function is not correct, just simulation The data. There are a lot of this kind of practice online, you can find yourself, (** Detailed introduction in the second chapter of this series).

con = mysql_connect (************* ********); .........} // Execute Data Query Statement Function & Query ($ SQL) {// $ Result = MySQL_QUERY ($ SQL); .... ............ // Return $ Result; if ($ SQL == "Select * from student where stu_clsid = 2") Return Array ("0" => Array ("stu_id" => 1, "stu_clsid" => 2, "stu_name" => "stu_name"), "1" => array ("stu_id" => 2, "stu_clsid" => 2, "stu_name" => "student2" )); DIE ("empty class");} // Get a number of query results Function Getone ($ SQL) {// $ results = mysql_query ($ sql); ............. // Return $ Result [0]; if ($ SQL == "SELECT * FORM CLAS WHERE CLS_ID = 1") Return NULL; if ($ SQL == "SELECT * FORM CLASS WHERE CLS_ID = 2") Return Array (" CLS_ID "=> 2," CLS_NAME "=>" ClassName "," CLS_ADDRESS "=>" ClassAddress ");} // Execute Database Update / Add / Remove Statement Function Execute ($ SQL) {// MySQL_QUERY ($ SQL) (Echo "
Inserting operation
...
Insert operation
"; r ETURN TRUE;}?> Test file 1, (modeltest1.php) (Query class label (CLS_ID) 2 class student list)

FindOnemodel ($ ClassID); $ data = & $ model-> getStudent (); Foreach ($ data as $ value) echo "Number:". $ value ["stu_id"]. " ------ Name: "$ value [" stu_name "]."
";> The result is:

No .: 1 ------ Name: student1 No .: 2 ------ Name: student2

Test file 2 (modeltest2.php) (Query class label (CLS_ID) is a list of students of 1 class)

FindOnemodel ($ ClassID); $ data = & $ model-> getStudent (); Foreach ($ data as $ value) echo "Number:". $ value ["stu_id"]. " ------ Name: "$ value [" stu_name "]."
";?>>

The result of returning is:

The class does not exist!

Test file three, (modeltest3.php) (add data to the Student table to the STUDENT table)

3, "stu_clsid" => 2, "stu_name" => "student3"); Require_once "./model/studentmodel.php"; $ data); Require_once" ./model/studentManager.php"; $Manager = New StudentManager ($ data); $ Result = $ manager-> INSERT ($ model); Echo $ Result? "

Insert operation successfully ": "

Insert operation failed ";?>>

The result of returning is:

Inserting operation ... Insert operation is successful

Test file four, (modeltest4.php) (Add data to the STUDENT table) 3, "stu_name" => "student3"); Require_once "./model/studentmodel.php"; $ data); need_once" ./model/studentmanager .php "; $ manager = new studentManager ($ data); $ result = $ manager-> INSERT ($ model); Echo $ Result?"

Insert operation successfully ":"

Insert operation Failure ";?>

The result of returning is:

The value of Stu_Clsid can't be empty

Result analysis:

The value of "match" "Match" in StudentModel is not empty, and the code in the code is $ data = array ("stu_id" => 3, "stu_name" => "student3); lacks the value of the STU_CLSID, so it cannot Check the error by the integrity of the data.

转载请注明原文地址:https://www.9cbs.com/read-6131.html

New Post(0)