Start your MVC with PHP (iii) implement your model layer

Source: Internet
Author: User
Tags class manager database join joins
Third, to achieve your mode layer

The model layer, which is the data processing layer in the MVC pattern, is used to mount the information and business logic, and design it to three concepts:
------Model class. is an entity class. Data that is used to hold all fields of one record in the database table. And you can verify the integrity of this record data.
------Modelmanager class. is the management class for the entity class. Typically, each entity class (Model) has a corresponding management class (Modelmanager). Management classes can be used to manage data records within an entity class (for example, delete/Add/change ...). However, the Modelmanager class does not necessarily have a corresponding model class.
------DB Class. Used to manage joins to a database. Modelmanager the operation of all data to the class. are implemented through this DB class. In the entire MVC pattern. Only this DB class can operate directly on the database. Also, only the Modelmanager class can invoke the DB class.

It looks like a bit of a hassle. But it's not really complicated. This model layer design method. The shopping cart program is very similar to the online shopping system. Model can be seen as the information class for a single item in a shopping cart. The manager can be viewed as an order. Orders are used to manage the purchase of goods.



The following is a simple example. should be more typical. Focus on his entire design and implementation of the process. Study it carefully. Actually, it's not difficult.

Note: All of the classes and methods used in the following example are simplified. The reality is much more complicated than this. But. As an example is already enough.


Folder structure:

|-db.php
|-model.php
|-manager.php
|-modeltest1.php
|-modeltest2.php
|-modeltest3.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 class (Class) Form, one is student (student) table,

Class table field: cls_id----------int--------NOT NULL
Cls_name--------string-----NOT NULL
Cls_address-----String-----NULL

Student table field: stu_id----------int--------NOT NULL
stu_clsid-------int--------NOT NULL
Stu_name--------String-----NULL


Classmodel.php inside is a class table of entity classes Classmodel
Classmanager.php inside is the Classmodel management class Classmanager
Studentmodel.php inside is an entity class of the student table Studentmodel
Studentmanager.php inside is the Studentmodel management class Studentmanager
Db.php inside is a database operations management class, he and inside the interface and the normal use of the same, but this example is only simulated to achieve this excuse. Therefore, you can run without a real database.


File 0: (model.php) base class for Model layer entities

<?php
base class used to wrap an information entity
Class model{
The data for this entity class,
Example:array ("id" =>1, "name" => "This is Name");
var $data;
The data constraint information of this entity class, used to determine the accuracy of the added $data data
See:classmodel
var $match;
The name of the table in the database corresponding to the entity
var $table;
Class
Function Model (& $data) {
$this->data = & $data;
}
Set a data for this entity to be a value
function set ($key, $value) {
$this->data[$key] = $value;
}
Get a data for this entity
function Get ($key) {
return $this->data[$key];
}
Get all the data for this entity
function GetData () {
return $this->data;
}
Get constraint information for this entity
function Getmatch () {
return $this->match;
}
Verifying the accuracy and integrity of entity data
function IsValid () {
foreach ($this->match as $key => $value) {
if (!isset ($value ["null"]) &&!isset ($this->data[$key])) die ("$key value cannot be null");
//..... Can be added to other judgments, such as whether it exceeds the maximum value, or the length is too long ...
}
}
}
?>


File 1: (manager.php) the base class for entity management in the model layer

<?php
Basic classes for managing entity information
Class manager{
Database Management class Objects
var $db;
Class
function Manager () {
$this->db = new db ();
}
Used to insert entity information into the database
function Insert (& $model) {
$model->isvalid ();
$table = $model->table;
$match = $model->getmatch ();
$data = $model->getdata ();
$str 1 = $str 2 = array ();
foreach ($match as $key => $value) {
if (Isset ($data [$key])) {
$str 1[] = $key;
$str 2[] = ($value ["type"]== "C")? "/" ". $data [$key]." /"": $data [$key];
}
}
$sql = "INSERT into $table (". Implode (",", $str 1). ") VALUES (". Implode (", ", $str 2).") ";
return $this->db->execute ($sql);
}
}
?>


Document 2: (classmodel.php) entity classes for class information

<?php
Entity classes that are used to wrap class information
Class Classmodel extends model{

var $data = array ();
$match,
Type is used to represent the types of data (I represents an integer and C is a string)
Name is used to represent the names of fields in the database table
Null indicates whether the value of the field is allowed to be null
(The array has a "null" =>true that is allowed to be null, otherwise it cannot be empty)
var $match = Array ("cls_id" => 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";
Class
Function Classmodel (& $data) {
Parent::model ($data);
}
Information used to get students in this class
function Getstudent () {
Require_once "./model/studentmanager.php";
$manager = new Studentmanager ();
$classId = $this->get ("cls_id");
Return $manager->getlist ($classId);
}
}
?>


Document 3: (studentmodel.php) entity classes for student information

<?php
Entity classes used to wrap student information
Class Studentmodel extends model{

var $data = array ();
$match,
Type is used to represent the types of data (I represents an integer and C is a string)
Name is used to represent the names of fields in the database table
Null indicates whether the value of the field is allowed to be null
(The array has a "null" =>true that is allowed to be null, otherwise it cannot be empty)
var $match = Array ("stu_id" => 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";
Class
Function Studentmodel (& $data) {
Parent::model ($data);
}
}
?>


Document 4: (classmanager.php) class entity management class

<?php
Management class for class entity information
Class Classmodelmanager extends manager{
Class
function Classmodelmanager () {
Parent::manager ();
}
Get class List
function &getlist () {
$sql = "SELECT * from class";
return $this->db->query ($sql);
}
Find and return entity classes for a class
function &findonemodel ($id) {
$sql = "SELECT * FORM class WHERE cls_id= $id";
$data = $this->db->getone ($sql);
if ($data ==null) Die ("This class does not exist.") ");
Require_once "./model/classmodel.php";
$model = new Classmodel ($data);
return $model;
}
}
?>


Document 5: (studentmanager.php) management class for student entities

<?php
Management class of student information entity
Class Studentmanager extends manager{
Class
function Studentmanager () {
Parent::manager ();
}
Get a list of students in a class
function &getlist ($classId) {
$sql = "SELECT * FROM student WHERE stu_clsid= $classId";
return $this->db->query ($sql);
}
}
?>


File 6: (db.php) database join management class for sharing and managing access to data. Since this class does not cover what is discussed in this chapter, this class simulates the "Real database Management class method", which is the same as the normal class, but the contents of the interface function are not correct, just simulated data. There are a lot of such practices on the Web, you can find it by yourself in the evening, (* * There are detailed introductions in the second chapter of this series).

<?php
Database Operations Management Class
Class db{
Database joins
var $con;
Class
function Db () {
$this->con=mysql_connect (********************); .....
}
Executing a 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" => "Student1"),
"1" =>array ("stu_id" =>2, "Stu_clsid" =>2, "Stu_name" => "Student2")
);
Die ("Empty Class");
}
Get a number of query results
function GetOne ($sql) {
$result = mysql_query ($sql); .............
return $result [0];
if ($sql = = "SELECT * FORM class 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");
}
Perform database update/Add/DELETE statements
function Execute ($sql) {
mysql_query ($sql);
echo "<br> insert operation <br>...<br> Insert operation complete <br>";
return true;
}
}
?>


Test Documents (modeltest1.php) (list of students who inquire class marking (CLS_ID) for Class 2)

<?php
Error_reporting (E_all);
Require_once "db.php";
Require_once "model.php";
Require_once "manager.php";

$classId = 2;

Require_once "./model/classmanager.php";
$manager = new Classmodelmanager ();
$model = $manager->findonemodel ($classId);
$data = & $model->getstudent ();
foreach ($data as $value)
echo "Number:". $value ["stu_id"]. "------Name:". $value ["Stu_name"]. " <br> ";
?>

The result returned is:

Item No: 1------Name: Student1
Item No: 2------Name: Student2


Test file Ii. (modeltest2.php) (list of students who inquire class marking (cls_id) as 1)

<?php
Error_reporting (E_all);
Require_once "db.php";
Require_once "model.php";
Require_once "manager.php";

$classId = 1;

Require_once "./model/classmanager.php";
$manager = new Classmodelmanager ();
$model = $manager->findonemodel ($classId);
$data = & $model->getstudent ();
foreach ($data as $value)
echo "Number:". $value ["stu_id"]. "------Name:". $value ["Stu_name"]. " <br> ";
?>


The result returned is:

The class does not exist.


Test file three, (modeltest3.php) (Perform insert work on database, add data to student table)

<?php
Error_reporting (E_all);
Require_once "db.php";
Require_once "model.php";
Require_once "manager.php";

$data = Array ("stu_id" =>3, "Stu_clsid" =>2, "Stu_name" => "Student3");
Require_once "./model/studentmodel.php";
$model = new Studentmodel ($data);
Require_once "./model/studentmanager.php";
$manager = new Studentmanager ($data);
$result = $manager->insert ($model);
echo $result? "?>

The result returned is:

Inserting operation in progress
...
Insert Operation complete

Insert Operation succeeded


Test File IV (modeltest4.php) (Perform insert work on database, add data to student table)

<?php
Error_reporting (E_all);
Require_once "db.php";
Require_once "model.php";
Require_once "manager.php";

$data = Array ("stu_id" =>3, "Stu_name" => "Student3");
Require_once "./model/studentmodel.php";
$model = new Studentmodel ($data);
Require_once "./model/studentmanager.php";
$manager = new Studentmanager ($data);
$result = $manager->insert ($model);
echo $result? "?>

The result returned is:

The Stu_clsid value cannot be empty

Results Analysis:

The "Match" in Studentmodel the STU_CLSID value is not NULL,
and code in Code $data = Array ("stu_id" =>3, "Stu_name" => "Student3");
The value of the Stu_clsid is missing, so the data integrity checksum is not possible.

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.