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
Part C — MVC Design Pattern with JavaScript, JQuery, AJAX, JSON, PHP and SQLite 2
Introduction 2
Technology Review 2
JavaScript Object Notation (JSON) 3
Asynchronous JavaScript and XML — AJAX 3
Pre-requirements for Lab 8 4
MVC Framework with JSON, AJAX, JQuery and PHP and SQLite 5
Example 1 — Accessing JSON based Web Services using JQuery, AJAX and JavaScript 5
Example 2 – Develop your own JSON based service and parse it through JQuery and AJAX 11
Example 3 – Data retrieval by selection from SQLite using AJAX, JQuery and PHP 15
Some Additional Exercises 26
Appendix 28
Appendix — Review results from Lab 7 28
Part C — MVC Design Pattern with JavaScript, JQuery, AJAX, JSON, PHP and SQLite
Introduction
The purpose of the previous Lab 7 Part A and Part B — MVC Design Pattern with PHP and SQLite — was to become familiar with MVC concepts by creating our own MVC framework. We continued our development in Part B by adding SQLite database connectivity. We created a database table, inserted new data and then retrieved and published already entered data from SQLite using the MVC framework.
For a review of Lab 7, see Appendix — Review results from Lab 7.
This Lab 8 tutorial continues to explore various uses of JavaScript, in particular the JQuery API with AJAX methods and PHP in your MVC framework.
There are many concepts covered in this Part C tutorial such as:
· Use of JQuery, AJAX and JSON to pass information via a service request or a service response without refreshing or leaving the webpage.
· Dealing with third party web services, such as Flickr as an example, to include third party data in our Web3D App site.
· While Flickr API, per se, may not be that useful, you are doing a Virtual Museum for your 3D App, and some of the larger museums do have their own API. So, it is entirely possible that you could choose 4 objects from a museum with their own API and use that to access data. Evidence of such in your assignment would count towards a deeper understanding.
· Returning a JSON object from the back end and parsing it in a handler to get meaningful data for the front end.
· Use JSON for data transfer between your server and 3D App pages.
And, there are many other functionalities you could develop.
Technology Review
Next, we will review, very briefly some of the technologies we are going to use in this Lab 8 Part C tutorial.
We have already covered SQLite in Lab 7, but just to remind you that SQLite is a ‘self-contained, embedded, full-featured, public-domain, SQL database engine — the most used database engine in the world’[footnoteRef:1]. Because SQLite is self-contained, i.e. an executable file, we can create instances of it in your public_html, which is easier to manage — further, ITS don’t offer us access to a MySQL instance. [1: https://www.sqlite.org/]
JavaScript Object Notation (JSON)
We have seen JSON files already, because we developed one in Lab 6, however in this tutorial we will read out data from the database using appropriate SQL methods and convert the resulting array of data into a JSON object using the PHP json_encode() method and then echo that JSON object to a waiting JavaScript handler.
Have a read through this small description of JSON http://en.wikipedia.org/wiki/JSON to make sure you are more familiar with JSON, and I have also written a short description in the Canvas 3D Apps — Technology Stack — MVC, AJAX, JSON and Data Stores section.
A JSON file structure looks something like that shown in Figure 1. Recall, we did some work on such JSON files in Lab 6.
Figure 1: Example JSON file for illustration purposes only
JSON contains a readable and easy to understand text, that can be compressed for faster data transfer over the network. You can create such a JSON file structure by hand, but often such a structure is created programmatically to avoid mistakes — largely because a JSON syntax error fails silently! However, there are many JSON validators online with which to check any JSON files you do create by hand. You can see from Figure 1 that a JSON file is largely composed of attribute, value pairs, e.g. “firstName”: “John”, can handle nesting “address”: {the address is a set of attribute:value pairs}, and arrays, e.g. “phoneNumber”: [ an array of phone numbers in {“attribute”: “value “}, { }].
Asynchronous JavaScript and XML — AJAX
Remember, AJAX (Asynchronous JavaScript and XML) which you touched on in when you created the gallery in Lab 5 and also in Lab 6 and 7, is method for receiving and transferring the data to and from a server in the background without refreshing a web page. As above, check out the Study Direct resources 3D Apps — Self-Learning section for more information.
JQuery is a client side-scripting library based on JavaScript that utilises AJAX methodology. This allows us to use many of JQuery’s built-in functionalities that might take a long time for us to develop. In short JQuery simplifies JavaScript for coders. As above, check out the Canvas 3D Apps — Technology Stack section for more information.
Pre-requirements for Lab 8
This Part C tutorial requires a very basic knowledge of PHP programming and the MVC design pattern along with JSON. If you have completed the MVC Part A and B of the Lab 7 tutorial then go ahead and complete this Lab 8 Part C, but if you haven’t finished Part A and B, then we strongly recommend you complete them before you start this Part C tutorial. Part C will be using the source code we developed in Part A and B.
MVC Framework with JSON, AJAX, JQuery and PHP and SQLite
Recall from Part A and B tutorials, where we created our MVC framework, let’s continue using the same MVC framework to progress further in terms of JSON and AJAX operations. But, before you start this tutorial, make a copy (backup) of your previous work so that you can use your last framework for another project you might to do in future. That is, create a Lab 8 part_c folder with a copy of your Lab 7 part_b work in it.
During this Lab Part C tutorial we will be developing three examples:
1. Accessing third party JSON based Web Services using JQuery, AJAX and JavaScript
2. Develop our own JSON based web service and parse it through JQuery and AJAX
3. Data retrieval by selection from SQLite using AJAX, JQuery and PHP
We will finish off with some suggested exercises to increase your skills.
Follow the step-by-step guide to continue building your MVC framework.
Example 1 — Accessing JSON based Web Services using JQuery, AJAX and JavaScript
These days, many web sites provide various functionalities through web services for other users to use in their own web sites. It is good practice to access these web services to enhance capabilities of our own sites. The goals of this exercise are to understand:
· How to get data from third party web services.
· How JQuery works.
· Reinforce your current practical knowledge of how AJAX works from Lab 6.
Let’s start by retrieving a JSON packet via AJAX and JQuery from a Flickr web service, parsing it through JavaScript and publishing it using HTML. Note, in these examples, we are not concentrating on presenting the HTML with particularly nice CSS, that’s down to you.
1. Modify your controller.php file inside your controller folder and add one new method named ‘apiGetFlickrService’ as shown in Figure 2:
Figure 2: Adding a apiGetFlickrService controller function
· Code explanation
· We have added another controller method named ‘apGetFlickrService’ to call only a view function named ‘viewFlickrService’.
· Note here that we are not accessing our Model class, instead we are going to access a third-party data using their API. That is, as you will see from Figure 4 we are bypassing the Model class. Is this a good idea? Does it conform to MVC design patterns?
2. Now you need to create 3 files: one named ‘viewFlickrService.php’ inside your view folder, and another flickrService.js for your js folder, see Figure 3. The 3rd file is, of course the CSS, which I am sure you can create yourself, or download from the Live Feedback Site. The operation of this code is shown in the sequence diagram in Figure 4
· We can see that the HTML invokes the JavaScript loadImages() method (or function), via the onclick() function.
· Further, we can also see from the sequence diagram that the Model class is bypassed completely. Effectively, the controller loads the view and the view makes a direct AJAX request to the Flickr web service, which returns a response direct to the view. So, is this strictly an MVC design pattern? Maybe, maybe not, but you could have a go, as an exercise, at converting the code to a more recognizable MVC design pattern.
· We leave this as an exercise for you to polish the code
· But, basically, you would need to use the jQuery .getJSON() method to call the Controller class method apiGetFlickrService() as before, but then as shown previously, invoke a PHP method in the Model class, e.g. $data = $this->model->apiGetFlickrService(); where you would need to create the apiGetFlickrService method in the Model class.
· This method in the Model class would simply use the Flickr API call:
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?
to return the image array in JSON format. You would decode the returned data using the PHP json_decode() function and PHP get_file_contents() function, and assign the result to a variable, e.g. $data. You can then pick off the data items you want, implying you need to know what the Flickr web service is returning (study the Flickr API) and assign this to an array variable, which you can return to the controller as you did in previous examples. Or, you could use the console.log() method to inspect the returned data first, then develop an appropriate handler.
· An important part of this process is to rough out your code to see what is returned from the web service because this allows you to inspect the returned JSON object using the console.log() function, you can then build the handler and set out your code MVC style.
· You can then convert the image array returned to the controller to a JSON object in the Controller class method, and load this into the view by echo’ing it out after loading the viewFlickrService.php view.
(a) viewFlickrService.php
(b) flickrService.js
Figure 3: (a) viewFlickrService.php and flickrService.js codes to implement the Flickr web service
Figure 4: Sequence diagram showing the operation of the getFlickrService process file
· Consider the sequence diagram in Figure 4 a bit a little more carefully. We could build a set of Model classes that invoke different third-party APIs, e.g. a Model class for the Flickr APIs, a Model class for the Victoria and API, a Model class for your SQLIte database.
· Similarly, In the same way we could have many different models, that had the same data, e.g. your coke, sprite and pepper data stored in an SQLite database, or a set of JSON files, or in a Firebase cloud, etc. But, your Controller class methods would be the same, as far as a front-end view was concerned. In your controller class you would simply declare your different model classes and write a controller API class with lots of methods to access the desired models. That is, your Controller class methods (i.e. your own API) would abstract out the different models (SQLite, JSON, Firebase).
· This is a great opportunity to get into the deeper understanding marks. I will leave you to consider this further, as an exercise, particularly for when you consider how you are going to organize the code based as an MVC design pattern for your final assignment.
· Code explanation (Figure 3) (a)
· Line 9: we define some CSS rules to style the image returned from the Flickr Web Service, you could use the CSS developed in previous labs, of course, e.g. img-thumbnail from Bootstrap 4! Or, download this file from the Live Feedback Site.
· Line 33: declares the jQuery library, we need this to access the $.getJSON() function. Remember, we used this in Lab 6.
· Line 34: declares your JavaScript code that defines the loadImages function that uses the Flickr web service.
· Line 16 to 18: we have created an input field with id txt and a default value for the search text.
· Line 26 to 28: we have created a button with title as ‘Search’, we have also added an event ‘onClick’ which invokes a function called loadImages().
· Code explanation (Figure 3) (b)
· Line 2 to 5: Normally, you would be developing all sorts of JS code here for your application including calling any functions you have developed, e.g. the loadImages() function In this particular case, if you call the load images function it triggers the Flickr service endpoint with random images, so we need a way to define an initial call. For example, set an initial search term in the HTML input tag for your Gallery theme; I set ‘Sprite’ line 17 in the viewFlickrService.php file. You may develop more sophisticated solution. Note JS functions have to be declared before they are called in JS, hence they are left outside the $(document).ready(function() method
· Line 6 to 37: is JavaScript code containing a loadImages() function
· Line 9: a variable named ‘txt’ has been declared and assigned value from the text field we created in our html code — notice we are using the document.getElementById function to get the value of the text input in the text box. We could have used a jQuery ID selector. That is, these are the same functionally:
var txt = document.getElementById(‘txt’).value;
var txt = $(‘#txt’).val();
· Line 14: The $.getJSON() function is a member of jQuery library, it uses AJAX to retrieve the Flickr image feed with parameters: tags, tagmode, and format
· Here we are passing a value typed in the input box to search the Flickr feed
· Flickr returns a JSON packet, since we defined format = json in our code
· Line 14: the function receives the resulting JSON object in data object.
· Line 16: Now, this is important, we use the console.log() function to examine the JSON object returned to see if there is any other data we might like to use. Look at the Object I the Chrome Inspect Tool.
· Line 18 to 22: in this case we have seen that the parameters in the JSON object might be useful in relation to the image array and each image returned. Actually, they are not that interesting, but it serves to illustrate.
· Line 25: we loop through all elements in data object
· Line 26 to 29: We build the HTML code as we did before in Lab 5 to include the media (images) received from the Flickr web service, a title and publications date.
· Line 32: we restrict the number of images to 4 (i.e. 0 to 3 elements from array) only — this is just an arbitrary number.
You should explore the Flickr API feed in more detail: http://www.flickr.com/services/feeds/docs/photos_public
3. Execute your newly created program to see the output
· Type any keyword such as: ‘cold coke’ click search, see Figure 5.
· Note: I have used a localhost in the URL, your URL could be different depending on hosting.
Note: Your Page was never refreshed, and the contents instantly appeared below the text field and the button, this is because we are using jQuery and AJAX features on our webpage above. Further, according to the simple CSS we created, the images are simply floating left, we could create more sophisticated CSS, of course, to better style the returned images. You can easily imagine a couple of improvements:
· Use Bootstrap 4 images components, particularly the img-thumbnail class to create a gallery of thumbnails, then use an open source lightbox, e.g. fancybox to present each thumbnail in a larger format.
· You could create a gallery of your own 3D model images created in 3ds Max, expanding or adapting your old gallery PHP code to create a gallery in your MVC framework. You might replace the XMLHttpRequest with a JQuery AJAX request, etc.
Finally, You can see this is a similar approach to the Image Gallery code you did in Lab 5, but instead of using XMLHttpRequest we have used the JQuery .getJSON method to make an AJAX request to Flicker’s web service. Now we have the JSON object back, we can strip out the date we want. You should be able to see that we can adapt this code to build a gallery as well, and we could change the HTML to use Bootstraps cards! Each card to hold a single image and associated data, set up Bootstrap rows and columns to hold the cards, build JS function to do the handler and ‘pass by value’ to set up row and column parameters
Alternatively, you could set images to Bootstrap thumbnails and build in lightbox functionality (fancybox).
Figure 5: The result from the apiGetFlickrService web service
Example 2 – Develop your own JSON based service and parse it through JQuery and AJAX
1. First, we need to create a JSON structure (a very simple one for this demo) and parse it through JavaScript. So, create a file named ‘createJson.php’ inside your ‘part_c/application/model’ folder and simply type the following JSON output shown in Figure 6. You can see that the JSON file is easily readable.
Figure 6: A simple JSON structure echo’d to the browser, this is really acting as a model
· Code explanation
· Nothing tricky, just one PHP echo statement to display a JSON packet on a browser. In reality, you would read such data from a database and write it to a JSON structure — see Example 3.
2. Now modify controller.php file and add another controller method see Figure 7.
Figure 7: A controller function to call a view that will use PHP to read the JSON
· Code explanation
· We have added another controller apiGetJson loads a view function named ‘viewJson’.
3. Create a new PHP file named viewJson.php and type the following code in it, see Figure 9, and save it in your view folder.
· Here, this time we are being particularly deviant, see Figure 8, because we are now bypassing the controller. The view, in effect, via the JavaScript code, is making an AJAX call direct to the createJson.php in the Model. Is this wrong, who’s to say?
Figure 8: Sequence diagram for the apiGetJson
· However, as above, and as an exercise, you could reorganize this code to better separate the model from the view via the controller. You should consider organizing your code so that the view invokes a method in the controller, which in turn invokes a method in the Model class (this is the request sequence), and then the model responds by sending the result back to the controller, whereby the Controller class method sends the result (or loads the view with the result) back to the view.
· This is the way you should do it for your assignment, and if you look at the code for Lab 9 on the Live Feedback Site, that is how we do it.
Figure 9: JavaScript code using JQuery .getJSON() to read the createJson.php
· Code explanation
· Line 11: contains reference to the latest JQuery library
· Line 15 to 33: makes an AJAX call with the jQuery $.getJSON function, with an ‘approachable’ path to the createJson.php file as a parameter. This should be a relative path.
· Line 20 to 26: we parse through the JSON packet and store HTML tags in a variable named ‘htmlCode’
· Line 29: we display the value of htmlCode on the ‘placeholder’ div located on line 8.
· Let’s see the output of our code, see Figure 10.
Figure 10: The resultant data displayed on the web page
Note: You can see from the output we have retrieved only the information we need from the JSON object, avoiding any unnecessary data, which we don’t need.
At this point it is worth reflecting a little on how to invoke calls to the Data Abstraction Layer, e.g. the PDO Objects, such as dbCreateTable, dbInsertData, dbGetData, and so on. In reality we are likely to use something like a JavaScript onclick=”myFunction()” (or JQuery .click()), where myFunction may exploit the JQuer
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com