别被标题吓着,本文来讨论如何用PHP+Jquery mobile 开发一个非Native的移动应用。
先来看看环境的搭配:PHP 环境(推荐5.1)+MYSQL+JQUERY MOBILE(当前版本)
好吧,写文章往往写的文字比代码还多!
--
-- 表categories,用来表示商品类别
--
CREATE TABLE `categories` (
`id` int(6) unsigned NOT NULL auto_increment,
`name` varchar(32) collate utf8_unicode_ci NOT NULL,
`contains` int(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;
--
--设置一些测试用的内容 `categories`(测试用)
--
INSERT INTO `categories` VALUES(1, '手记本', 3);
INSERT INTO `categories` VALUES(2, '智能手机', 4);
INSERT INTO `categories` VALUES(3, '平板电脑', 4);
-- --------------------------------------------------------
--
-- 表:产品表 `products`
--
CREATE TABLE `products` (
`id` int(6) unsigned NOT NULL auto_increment,
`category` int(6) unsigned NOT NULL,
`name` varchar(32) collate utf8_unicode_ci NOT NULL,
`manufacturer` varchar(32) collate utf8_unicode_ci NOT NULL,
`price` int(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `category` (`category`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=12 ;
--
-- 设置一些测试数据
--
INSERT INTO `products` VALUES(1, 1, 'MacBook Air', '苹果', 999);
INSERT INTO `products` VALUES(2, 1, 'MacBook Pro', '苹果', 1500);
INSERT INTO `products` VALUES(3, 1, 'Vaio', '索尼', 899);
INSERT INTO `products` VALUES(4, 2, 'iPhone 4', '苹果', 650);
INSERT INTO `products` VALUES(5, 2, 'Galaxy S2', '三星', 620);
INSERT INTO `products` VALUES(6, 2, 'Incredible S', 'HTC', 560);
INSERT INTO `products` VALUES(7, 2, 'Sensation', 'HTC', 590);
INSERT INTO `products` VALUES(8, 3, 'iPad 2', '苹果', 500);
INSERT INTO `products` VALUES(9, 3, 'Galaxy Tab', '三星', 480);
INSERT INTO `products` VALUES(10, 3, 'Eee Pad', '华硕', 400);
INSERT INTO `products` VALUES(11, 3, 'Iconia Tab', '宏基', 480);
好吧,我们一向强调写的少,做的多,开始从 index.php 开始。
<?php
/*
作为应用入口
*/
defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/');
require_once "includes/main.php";
try {
if($_GET['category']){
$c = new CategoryController();
}
else if(empty($_GET)){
$c = new HomeController();
}
else throw new Exception('出错了,没找到您要的功能!');
$c->handleRequest();
}
catch(Exception $e) {
//仅用 "render()" 方法来显示异常页面
render('error',array('message'=>$e->getMessage()));
}
?>
这里所引用的的 includes/main.php 内容如下:
<?php
/*
这其实是为了保证 index.php 看上去不会太长
*/
require_once "includes/config.php";
require_once "includes/connect.php";
require_once "includes/helpers.php";
require_once "app/models/product.model.php";
require_once "app/models/category.model.php";
require_once "app/controllers/home.controller.php";
require_once "app/controllers/category.controller.php";
// 设置浏览器的缓存
header('Cache-Control: max-age=3600, public');
header('Pragma: cache');
header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");
?>
好,一步一步来,includes/config.php的内容:
<?php
error_reporting(E_ALL ^ E_NOTICE);
/*=========== Database Configuraiton ==========*/
$db_host = '127.0.0.1';
$db_user = 'root';
$db_pass = '123456';
$db_name = 'jstore';
/*=========== 一些网站信息 ==========*/
$defaultTitle = '移动网上商店';
$defaultFooter = date('Y').' © 版权所有:水墨剑客';
?>
includes/connect.php 人内容:
<?php
/*
创建 PDO 类(注意,只有PHP版本5以上才能用).
登陆数据库的详细信息来自 config.php.
*/
try {
$db = new PDO(
"mysql:host=$db_host;dbname=$db_name;charset=UTF-8",
$db_user,
$db_pass
);
$db->query("SET NAMES 'utf8'");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
error_log($e->getMessage());
die("发生了一个数据库方面的错误,所以不能继续。");
}
?>
基于MVC结构应该有个宣染视图的功能。
includes/helpers.php 的内容:
<?php
function render($template,$vars = array()){
extract($vars);
if(is_array($template)){
foreach($template as $k){
$cl = strtolower(get_class($k));
$$cl = $k;
include APP_PATH."app/views/_$cl.php";
}
}
else {
include APP_PATH."app/views/$template.php";
}
}
function formatTitle($title = ''){
if($title){
$title.= ' | ';
}
$title .= $GLOBALS['defaultTitle'];
return $title;
}
?>
我们再来看看 app/models/product.model.php 的内容:
<?php
class Product{
public static function find($arr){
global $db; //使用全局变量
if($arr['id']){
$st = $db->prepare("SELECT * FROM products WHERE id=:id");
}
else if($arr['category']){
$st = $db->prepare("SELECT * FROM products WHERE category = :category");
}
else{
throw new Exception("Unsupported property!");
}
$st->execute($arr);
return $st->fetchAll(PDO::FETCH_CLASS, "Product");
}
}
?>
看上去并不难.
同样结构的 app/models/category.model.php:
<?php
class Category{
public static function find($arr = array()){
global $db;
if(empty($arr)){
$st = $db->prepare("SELECT * FROM categories");
}
else if($arr['id']){
$st = $db->prepare("SELECT * FROM categories WHERE id=:id");
}
else{
throw new Exception("Unsupported property!");
}
$st->execute($arr);
// Returns an array of Category objects:
return $st->fetchAll(PDO::FETCH_CLASS, "Category");
}
}
?>
好,我们来看看 app/controllers/home.controller.php :
<?php
class HomeController{
public function handleRequest(){
$content = Category::find();
render('home',array(
'title' => '欢迎来到网站商店',
'content' => $content
));
}
}
?>
作为首页,显示所有产品类别是可以让人接受的。
这里使用 render 函数,当然要看看 view 模板:home.php的内容
<?php render('_header',array('title'=>$title))?>
<p>欢迎! 仅作为演示.</p>
<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
<li data-role="list-divider">请选择一个类别</li>
<?php render($content) ?>
</ul>
<?php render('_footer')?>
这里高亮的部分就是 Jquery mobile 要用的
解读一下第一个 render 函数会调用 _header.php 内容为:
<!DOCTYPE html>
<html>
<head>
<title><?php echo formatTitle($title)?></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
<link rel="stylesheet" href="assets/css/styles.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-theme="b">
<a href="./" data-icon="home" data-iconpos="notext" data-transition="fade">起始</a>
<h1><?php echo $title?></h1>
</div>
<div data-role="content">
作为第二个 render 会调用 _category.php
<li <?php echo ($active == $category->id ? 'data-theme="a"' : '') ?>>
<a href="?category=<?php echo $category->id?>" data-transition="fade">
<?php echo $category->name ?>
<span class="ui-li-count"><?php echo $category->contains?></span></a>
</li>
第三个 render 嘛,嗯 _footer.php 内容为:
</div>
<div data-role="footer" id="pageFooter">
<h4><?php echo $GLOBALS['defaultFooter']?></h4>
</div>
</div>
</body>
</html>
看上去像半截,不过我相信你会理解的。
到此我们的首面功能应该完成了,顺便贴上 assets/css/styles.css 代码:
.product i{
display:block;
font-size:0.8em;
font-weight:normal;
font-style:normal;
}
.product img{
margin:10px;
}
.product b{
position: absolute;
right: 15px;
top: 15px;
font-size: 0.9em;
}
.product{
height: 80px;
}
@media all and (min-width: 650px){
.rightColumn{
width:56%;
float:right;
margin-left:4%;
}
.leftColumn{
width:40%;
float:left;
}
}