(转载)Building a Website with PHP, MySQL and jQuery Mobile, Part 1

In this two-part tutorial, we will be building a simple website with PHP and MySQL, using the Model-View-Controller (MVC) pattern. Finally, with the help of the jQuery Mobile framework, we will turn it into a touch-friendly mobile website, that works on any device and screen size.

In this first part, we concentrate on the backend, discussing the database and MVC organization. Next time, we will be writing the views and integrating jQuery Mobile.

The File Structure

As we will be implementing the MVC pattern (in effect writing a simple micro-framework), it is natural to split our site structure into different folders for the models, views and controllers. Don’t let the number of files scare you – although we are using a lot of files, the code is concise and easy to follow.

The Directory Structure

The Directory Structure

The Database Schema

Our simple application operates with two types of resources – categories and products. These are given their own tables – jqm_categories, and jqm_products. Each product has a category field, which assigns it to a category.

jqm_categories Table Structure

jqm_categories Table Structure

The categories table has an ID field, a name and a contains column, which shows how many products there are in each category.

jqm_products Table Structure

jqm_products Table Structure

The product table has a namemanufacturerprice and a category field. The latter holds the ID of the category the product is added to.

You can find the SQL code to create these tables in tables.sql in the download archive. Execute it in the SQL tab of phpMyAdmin to have a working copy of this database. Remember to also fill in your MySQL login details in config.php.

The Models

The models in our application will handle the communication with the database. We have two types of resources in our application – products and categories. The models will expose an easy to use method –find() which will query the database behind the scenes and return an array with objects.

Before starting work on the models, we will need to establish a database connection. I am using the PHP PDO class, which means that it would be easy to use a different database than MySQL, if you need to.

includes/connect.php
01 /*
02     This file creates a new MySQL connection using the PDO class.
03     The login details are taken from includes/config.php.
04 */
05  
06 try {
07     $db new PDO(
08         "mysql:host=$db_host;dbname=$db_name;charset=UTF-8",
09         $db_user,
10         $db_pass
11     );
12  
13     $db->query("SET NAMES 'utf8'");
14     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
15 }
16 catch(PDOException $e) {
17     error_log($e->getMessage());
18     die("A database error was encountered");
19 }

This will put the $db connection object in the global scope, which we will use in our models. You can see them below.

includes/models/category.model.php
01 class Category{
02  
03     /*
04         The find static method selects categories
05         from the database and returns them as
06         an array of Category objects.
07     */
08  
09     public static function find($arr array()){
10         global $db;
11  
12         if(empty($arr)){
13             $st $db->prepare("SELECT * FROM jqm_categories");
14         }
15         else if($arr['id']){
16             $st $db->prepare("SELECT * FROM jqm_categories WHERE id=:id");
17         }
18         else{
19             throw new Exception("Unsupported property!");
20         }
21  
22                 // This will execute the query, binding the $arr values as query parameters
23         $st->execute($arr);
24  
25         // Returns an array of Category objects:
26         return $st->fetchAll(PDO::FETCH_CLASS, "Category");
27     }
28 }

Both models are simple class definitions with a single static method – find(). In the fragment above, this method takes an optional array as a parameter and executes different queries as prepared statements.

In the return declaration, we are using the fetchAll method passing it the PDO::FETCH_CLASS constant. What this does, is to loop though all the result rows, and create a new object of the Category class. The columns of each row will be added as public properties to the object.

This is also the case with the Product model:

includes/models/product.model.php
01 class Product{
02  
03     // The find static method returns an array
04     // with Product objects from the database.
05  
06     public static function find($arr){
07         global $db;
08  
09         if($arr['id']){
10             $st $db->prepare("SELECT * FROM jqm_products WHERE id=:id");
11         }
12         else if($arr['category']){
13             $st $db->prepare("SELECT * FROM jqm_products WHERE category = :category");
14         }
15         else{
16             throw new Exception("Unsupported property!");
17         }
18  
19         $st->execute($arr);
20  
21         return $st->fetchAll(PDO::FETCH_CLASS, "Product");
22     }
23 }

The return values of both find methods are arrays with instances of the class. We could possibly return an array of generic objects (or an array of arrays) in the find method, but creating specific instances will allow us to automatically style each object using the appropriate template in the views folder (the ones that start with an underscore). We will talk again about this in the next part of the tutorial.

There, now that we have our two models, lets move on with the controllers.

Computer Store with PHP, MySQL and jQuery Mobile

Computer Store with PHP, MySQL and jQuery Mobile

The controllers

The controllers use the find() methods of the models to fetch data, and render the appropriate views. We have two controllers in our application – one for the home page, and another one for the category pages.

includes/controllers/home.controller.php
01 /* This controller renders the home page */
02  
03 class HomeController{
04     public function handleRequest(){
05  
06         // Select all the categories:
07         $content = Category::find();
08  
09         render('home',array(
10             'title'     => 'Welcome to our computer store',
11             'content'   => $content
12         ));
13     }
14 }

Each controller defines a handleRequest() method. This method is called when a specific URL is visited. We will return to this in a second, when we discuss index.php.

In the case with the HomeControllerhandleRequest() just selects all the categories using the model’s find() method, and renders the home view (includes/views/home.php) using our render helper function (includes/helpers.php), passing a title and the selected categories. Things are a bit more complex inCategoryController:

includes/controllers/category.controller.php
01 /* This controller renders the category pages */
02  
03 class CategoryController{
04     public function handleRequest(){
05         $cat = Category::find(array('id'=>$_GET['category']));
06  
07         if(empty($cat)){
08             throw new Exception("There is no such category!");
09         }
10  
11         // Fetch all the categories:
12         $categories = Category::find();
13  
14         // Fetch all the products in this category:
15         $products = Product::find(array('category'=>$_GET['category']));
16  
17         // $categories and $products are both arrays with objects
18  
19         render('category',array(
20             'title'         => 'Browsing '.$cat[0]->name,
21             'categories'    => $categories,
22             'products'      => $products
23         ));
24     }
25 }

The first thing this controller does, is to select the category by id (it is passed as part of the URL). If everything goes to plan, it fetches a list of categories, and a list of products associated with the current one. Finally, the category view is rendered.

Now lets see how all of these work together, by inspecting index.php:

index.php
01 /*
02     This is the index file of our simple website.
03     It routes requests to the appropriate controllers
04 */
05  
06 require_once "includes/main.php";
07  
08 try {
09  
10     if($_GET['category']){
11         $c new CategoryController();
12     }
13     else if(empty($_GET)){
14         $c new HomeController();
15     }
16     else throw new Exception('Wrong page!');
17  
18     $c->handleRequest();
19 }
20 catch(Exception $e) {
21     // Display the error page using the "render()" helper function:
22     render('error',array('message'=>$e->getMessage()));
23 }

This is the first file that is called on a new request. Depending on the $_GET parameters, it creates a new controller object and executes its handleRequest() method. If something goes wrong anywhere in the application, an exception will be generated which will find its way to the catch clause, and then in the error template.

One more thing that is worth noting, is the very first line of this file, where we require main.php. You can see it below:

main.php
01 /*
02     This is the main include file.
03     It is only used in index.php and keeps it much cleaner.
04 */
05  
06 require_once "includes/config.php";
07 require_once "includes/connect.php";
08 require_once "includes/helpers.php";
09 require_once "includes/models/product.model.php";
10 require_once "includes/models/category.model.php";
11 require_once "includes/controllers/home.controller.php";
12 require_once "includes/controllers/category.controller.php";
13  
14 // This will allow the browser to cache the pages of the store.
15  
16 header('Cache-Control: max-age=3600, public');
17 header('Pragma: cache');
18 header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
19 header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");

This file holds the require_once declarations for all the models, controllers and helper files. It also defines a few headers to enable caching in the browser (PHP disables caching by default), which speeds up the performance of the jQuery mobile framework.

Stay tuned for part two!

With this the first part of the tutorial is complete! Stay tuned for next week’s addition, where we will be writing the views and incorporate jQuery Mobile. Feel free to share your thoughts and suggestions in the comment section below.

http://tutorialzine.com/2011/08/jquery-mobile-product-website/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值