Dr Martin White
Mobile Web 3D Applications
MVC Design Pattern with PHP and SQLite
Copyright By PowCoder代写 加微信 powcoder
MVC Design Pattern with PHP and SQlite
Table of Contents
Introduction 2
Part A — MVC Framework with PHP 3
Building an MVC Framework using PHP 3
Controller 6
Test the basic MVC framework 11
Add images to the view 11
Test the updated MVC framework 15
Part B — Adding SQLIte with PHP to the MVC Framework 17
Building an MVC Framework using PHP and SQLite 18
Starting to use SQLite 19
Add more methods to your controller 21
Test your controller code 24
Connect up the SQLite database 25
Develop our views 33
Test your new MVC code 35
Some improvements 36
Laboratory 8 38
Introduction
The purpose of this Week 7 tutorial is to introduce you to the concept of a model, view, controller (MVC) design pattern or framework, which you will implement as part of your 3D App design. You will convert your Lab 6 3D App SPA into a MVC design pattern using this framework.
Unfortunately, it takes a lot more time to format code in these tutorials, and this tempts you to cut and paste for the word document, which can lead to errors. So, as usual, I will rely on screenshots of most of the code, and you should consult the Live Feedback Site for a working version of Lab 7. However, as the back end will be written in PHP, which is on the server-side you won’t be able to see the actual PHP code!
So, as we are at week 7, and many of you will be catching up, you should not forget that all lab tutorial codes are available for download on GitHub, see Part 6: Set up Git and GitHub with Visual Studio Code in the Lab 1 tutorial. You will then be able to cut and paste, where appropriate. However, to download, you will need a GitHub account, unless you are happy to type all the code in again from the screen shots! But, do not just download it and expect it to run, you will have to integrate it into your Lab 6 results! You can download the tutorial code from https://github.com/martinwh/3D_Apps_2019 in the Lab 7 folder.
Having two screens while completing this tutorial is very useful, because you can have the tutorial text open, the Lab 7 MVC code from GitHub in a separate code editor, so that you can see it as you read this tutorial, and then develop in another code editor — or use a code editor that has more than one window.
Part A — MVC Framework with PHP
Part A of this tutorial explores the development of a simple MVC framework written in PHP to implement our 3D App SPA.
The ‘3D Apps — Technology Stack’ section on MVC, AJAX, JSON, and Data Stores (see Canvas) discusses MVC in more detail. During this laboratory, we will be developing our own very simple MVC framework.
So, through this tutorial and some background research you should become familiar with the Model, View, Controller (MVC) design pattern. You are about to develop this simple MVC framework using the following technology stack: HTML5, CSS3, JavaScript, JQuery at the front-end connecting via jQuery and AJAX to a PHP and SQLIte back-end — along with libraries such as Bootstrap 4.
There are, of course, other variants of MVC, but we will stick with MVC for this Lab 7 Tutorial. Similary, Instead of building our own PHP based MVC framework, there are many web frameworks (both PHP and Java based) we could choose from, but it is more instructive to develop our own simple version so that you can better understand the concepts. You can explore and experiment with other MVC frameworks, such as CodeIgnitor, Laravel and SLIM (a micro framework for PHP), but it is more instructive to develop our own simple version so that you can better understand the concepts.
In this tutorial, we will use the MVC design pattern whereby a view makes a request to a controller, which then invokes a model to retrieve data from a data store (or model, which could be a JSON file, SQLite database, or a third-party API endpoint) and passes a response back to the controller, which then updates the view to publish the response (e.g. your 3D App data) on a web browser.
This tutorial will demonstrate how easy it is to replace a view from a website without any modifications to the model and virtually no modifications to the controller, which is possible with MVC design patterns as it effectively separates out the data (or model) from the business logic (the control) and the web visualisation (or view).
Note, we will not simply create bits of PHP code to access your 3D App data from the SQLite database, neither shall we use procedural PHP. Instead, we will use classes and objects in PHP (later versions of PHP are object oriented), and although these are just simply introduced here some background reading may be needed if you are not familiar with object oriented PHP. Here is a very short, but nice example of procedural PHP versus object oriented PHP on GitHub.
Further, we will also introduce the notion of data-access abstraction using PDO (PHP Data Objects). The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.
Building an MVC Framework using PHP
During this tutorial, you will learn how to build your own extremely lightweight PHP framework based around the MVC (model-view-control) architecture or design pattern using object oriented PHP.
We will use a step by step approach:
1. Start by creating a new folder for Lab 7, e.g. call it Lab 7, whatever. However, unlike before don’t copy over your Lab 6 yet, up to now we have been evolving the previous week’s lab into the next one. Instead, we will start to create the model and view components of the MVC framework. Your view(s), will of course be the based on your current index.html template for lab 6, however this will become a view in the view folder of the upcoming MVC folder structure. As before, you will need a live website environment to test your new MVC based 3D App, for example:
· You may already be using a localhost environment on your own PC or laptop, e.g. WAMP, MAMP, XAMPP or even the Mac built-in apache web server.
· You may instead be using your public_html environment as your Local Folder (if you haven’t got this set up yet — I noticed in Lab 6 some of you still did not have this set up — simply do a search on Google for something like: ‘Sussex ITS Web Space’ and follow the instructions to set up your ITS web space.
2. Create a file named as ‘index.php’ using any text editor, e.g. Notepad++, Brackets, Sublime Text (I am currently using Visual Studio Code, for which I have already discussed in lab 1 that it is easy to integrate with GitHub — a version control repository and hosting system.
· Now type the following lines of code in ‘your index.php’ file, Figure 1.
· Note, when I say ‘type’, you can of course type, but if you have downloaded the tutorial code, as indicated at the start, from GitHub, you can simply ‘cut and paste’.
Figure 1: The index.php file
· Code explanation
· Line 1 and 11: ‘’ denotes the end of the PHP code.
· Anything after ‘//’ is treated as comments, and these are only used for code readability. The PHP compiler (embedded in the browser) will simply ignore the whole line, starting from the ‘//’ characters.
· We have added these some comment lines to show how to use comments in your PHP code.
· Line 5 and 6: The PHP library function ‘error_reporting()’ and ‘ini_set()’ enables debugging of your code, i.e. any errors generated will display when your PHP script has any bugs. If you remove this, you will not be able to see any errors in your code and your browser will block the site in the case of any error in your code — you will simply be left scratching your head wondering where the bug is! So, it is very important that you keep these functions in your code to see any error reporting during PHP code development. As the PHP functions we will develop are relatively simple we will manage with this error reporting, but for anything more sophisticated you might want to introduce other PHP debugging options, which range from printing out variables, building a console_log function, to including a debugging library.
· Line 10: The require ‘application/mvc.php’; tells the browser to load or include a file named ‘mvc.php’ from the ‘application’ folder into the current file.
· Effectively, this index.php file is acting as a configuration file to define global variables and URL includes, since this file is the starting point of our site.
3. Create a folder called ‘application’ inside your ‘’ folder
4. Then create three subfolders inside the ‘application’ folder, called: controller, model, and view
· Your folder structure should now look like that shown in Figure 2.
Figure 2: Set up for the MVC folder structure on a Mac, should be a similar structure on a PC
· As you can see, we now have three different folders to hold your application’s ‘model’, ‘view’ and ‘controller’; we will make sure that we store:
· The data access code inside the ‘model’ folder — this will be a model class with methods to access the data store, e.g. the SQLite database
· Front end presentation code in the ‘view’ folder — this your existing index.html (Lab 6) file, but we will rename it view.php, or something like that.
· And, business logic or control code in the ‘controller’ folder — this will be a PHP class with methods that invoke your model class methods
· Your getJsonData.js file will be re-written to make AJAX calls to these PHP methods in the controller using the JQuery .getJSON() function.
5. Before we create code inside those model, view, controller folders, Figure 2., let’s create an entry point for our application. This PHP file will refer to all three components, model, view and controller and it will initialize (create an instantiation) the controller of our application.
6. Create a PHP file inside the ‘application’ folder and name it as ‘mvc.php’
· Now type the following code in it and save the file, Figure 3.
Figure 3: The PHP entry point file — mvc.php
· Code explanation
· Lines 3, 4 and 5 are code to include the three different files from the three folders (model, view and controller folders), these statements will include three PHP files (load.php, model.php and controller.php). This means from this point we can use any function or variables from within these three files (load.php, model.php and controller.php) in our application.
· Just as we included with the ‘require’ in the index.php the mvc.php file so at this level inside the mvc.php we include other php files.
· Line 6: Initializes the controller, by creating its object / instance.
· Note we didn’t call the file in the view folder view.php. Why do you think that is? It is because we might have many views and we will use the load.php file to select and load the views.
Controller
Now let’s create our core components of the MVC framework.
7. Create a PHP file inside the ‘controller’ folder and name it as ‘controller.php’
· Create the following code in the controller.php file, see Figure 4.
Figure 4: The PHP controller file
· Code explanation
· Lines 2 to 23: defines a class called ‘Controller’. Everything between parentheses ‘{‘ and ‘}’ is the body of the class.
· Class definition: PHP gives us a very simple way to define an object as a class, which may contain its own constants, variables (called properties) and functions (called methods). A class is effectively a wrapper around the object that defines and encapsulates the object’s properties and methods. The class represents the PHP interface that allows you to interact and modify the object. You can create multiple instances/objects of one class, each object has separate memory space and has a separate copy of all members defined in that class, hence is reusable. A class can have many or no methods, we usually use these methods to set, modify and get properties from the object.
· Lines 6 and 7: Defines ‘load’ and ‘model’ variables, and since they are declared as ‘public’, they can be accessed from anywhere using the instance of the class.
· Lines 10 to 17: We define a constructor of the class, again everything between parentheses ‘{‘ and ‘}’ is the body of constructor.
· Constructor definition: A constructor is the first function that is executed when a class is initialized. This means anything in constructor will execute immediately as soon as we create an instance of the class.
· In this example, the constructor function creates new objects for load() and model(), see below, and then calls the home() method (or function), which gets the car data from the model3D_info() model and presents it in the view3DAppTest view.
· The two underscores before the constructor method indicate that PHP is treating this construct method as magical, you should not use a double underscore for any of your own methods/functions.
· With OO PHP, all PHP objects (classes) have a special built-in method called a constructor that allows you to initialise your properties, i.e. give your properties values, when you instantiate, i.e. create, an object. Note that: functions = methods, and variables = properties
· Note, if you create a constructor, and you don’t have to, but it is very useful to initialise properties, the PHP will automatically call the __construct() method/function when you create an object from your class.
· The constructor can be by passed by specifically calling the Home function in a URL?
· ‘$this’ refers to the current object of the class, so that
$this->load and $this->model
means we are accessing the ‘load’ and ‘model’ variables from the current class objects instantiated with the new Load() and new Model().
· ‘new Load()’ defines a definition of new object of the class named ‘Load’.
· Similarly ‘new Model()’ defines a definition of new object of the class named ‘Model’. Note we have not written the Load and Model classes yet; we will define these two classes inside ‘model’ and ‘view’ folders below.
· ‘$this->home()’ refers to the home function from the current class object.
· Lines 19 to 25: contain a definition of the ‘home’ function.
· Line 22: ‘model3D_info()’ is a call to a function from the model class for the current object. The function model3D_info() returns value(s) that is/are stored in a test ‘data’ variable or array.
· Line 24: similarly ‘view(‘view3DAppTest’, $data)’ is a call to the function named ‘view’ from load object.
· ‘view3DAppTest’ and $data are the parameters passed to the view function.
We now need to create some model code to simulate the database contents.
8. So, create another file called ‘model.php’ inside ‘model’ folder, and type following code in it, see Figure 5.
Figure 5: The PHP Model file
· Code explanation
· Lines 2 to 16: defines a class called ‘Model’. Everything between parentheses ‘{‘ and ‘}’ is the body of the class. You can immediately see that we simply simulating a data store by populating an array with data to return to the calling function.
· Recall: a class is a wrapper around the concept of an object, which contains variables (properties) and functions (methods). A user can create multiple instances/objects of one class, and each object has separate memory space and also has a separate copy of all members defined in that class.
· We have not written a constructor method for Model, so the function model3D_info() will default to the construct method, that is when you instantiate this object Model, the function model3D_info() will execute.
· Lines 4 to 15: contains definition of the function named ‘model3D_info’
· Lines 7 to 14: defines an array, which is not stored in any variable at this stage but its reference is returned to the function calling statement.
· This array has five values ( 3D Image 1, …) and five pointers (model1, …) to those values.
· Later, this array will also hold data for some images, which we will with a second view to illustrate the loading of different views using data from the model.
Note: At this stage, we are just simulating a database in the model class. We can use this class to communicate with an actual database to retrieve any data; once we have the data from database, it can then be passed in similar way to ‘view’ class to publish on a browser.
Now let’s create our view. Since in this tutorial we are going to create two different views for the same class, we need two different HTML files and one intermediary load.php file to select between those two views according to the instructions provided by the controller.
9. So, create a file named ‘load.php’ inside the ‘view’ folder. You can begin to see now why we called this file load.php and not view.php. The role of load.php will be to load a view, where a view will be an html file.
· Now type the following code in the load.php file, see Figure 6
Figure 6: The PHP load file
· Code explanation
· Lines 2 to 15: defines a class called ‘Load’.
· As before, the function view defaults to the construct method, because we haven’t specifically created the __contruct() method.
· Everything between parentheses ‘{‘ and ‘}’ is the body of the class.
· Lines 3 to 14: defines a function (or method) called ‘view’.
· Everything between parentheses ‘{‘ and ‘}’ is the body of the function.
· Line 8: the ‘if’ statement checks the ‘$data’ variable to see if it is a pointer to an array? If it is a pointer to an array, the program control goes to line 9, if it is not pointer to an array the program control will skip line 9.
· Line 9: a predefined php function named ‘extract’ is used to import all variables from an array into the current file, so that our view can use them as variables rather than array elements.
· Line 13: includes value of the variable $file_name provided as an argument to view function.
· Remember: in the controller class line number 24, we passed the ‘view3DAppTest’ string to the ‘view’ function, so in above case the value of the variable ‘$file_name’ is ‘view3DAppTest’.
· Succeeding the variable $file_name there is a ‘.’ character, which is used for concatenation of two strings. In above case the value of $file_name (which should be ‘view3DAppTest’) is concatenated with ‘.php’ string, and the resulting string becomes ‘view3DAppTest.php’.
10. Create another file, save as ‘view3DAppTest.php’ also inside the same ‘view’ folder, and type the following HTML code in it, see Figure 7.
Figure 7: The PHP view3DAppTest file
· Code explanation
· The code above is mostly HTML code except between lines 9 to 15. You should already be familiar with some simple HTML code, so we won’t explain this in more detail.
· Lines 12 to 17: the PHP statement ‘echo’ is used for displaying a text on the browser. In the above case, the values of variables $model1 to $model6 are displayed on the browser and after each output a line break is inserted by concatenating ‘
’ in the echo statement.
Test the basic MVC framework
11. Now let’s execute our code, by typing our website url into any internet browser, see Figure 8.
· Note: You cannot simply double click on a php to run in a browser, you will need a php server to see its output. You should have been provided a PHP hosting space by ITS, which should be your ‘public_html’ folder.
· Alternatively, use a localhost on your own PC or laptop.
Figure 8: The HTML output generated by the view
Note: the url above is ‘http://localhost:8888/’, since I am running on my Mac’s localhost, but it will be different in your case. If you are using your public_html folder on your ITS hosting space, your URL should be something like this:
· users.sussex.ac.uk/~your-user-name/3dapp/lab7 /index.php
· In the above output, the data comes from the model and is displayed in the view, and the controller has coordinated between these two components.
Add images to the view
In this section, we will use some of your 3D images as data. We will create a new view called view3DAppTest_2.php, and we will update our model test data to reference the images.
Carry on following the ste
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com