search
HomeBackend DevelopmentPHP TutorialThinkPHP Mobile使用方法简明教程_php实例

一、基础知识

1.手机APP的类型

移动端的应用有这几种:WebApp,NativeApp,HybridApp。

WebApp 就是手机网站,需要用手机浏览器访问。

NativeApp是用原生语言开发,用户需要下载安装的手机应用。 NativeApp的开发成本很高,每个平台的开发语言都不一样, 比如IOS的开发语言是object C , Android系统的APP需要用Java开发, WindowsPhone 则需要用 C# 开发。那么我们如果需要做一个多平台都能运行的APP,需要用多种语言重复开发多次。
相对于NativeApp来说, WebApp开发就简单多了, 用html,css,js就可开发WebApp, 而且开发一次跨多个平台。但是WebApp 需要用户打开手机浏览器输入网址才能访问,而且不能像NativeApp 能调用手机的摄像头,通讯录等功能。WebApp的html,css,js图片等静态资源在服务器上,用户需要下载,会消耗用户更多的流量。 而NativeApp的静态资源在手机本地。

HybridApp中和了NativeApp和WebApp各自的优势。 我们可以用html,css,js 开发,兼容多个平台。用户也要下载安装,并能调用手机的摄像头、通讯录等功能, HybridApp的静态资源也在手机本地。

我们知道ThinkPHP的模板也是用HTML,CSS,JS 开发的。所以我们想能否将ThinkPHP的模板直接打包成手机APP?让我们能一次开放同时拥有电脑版网站,手机版网站和手机APP, 因此才有了TPM的诞生。TPM能让我们将ThinkPHP的模板打包成一个HybridApp。

2.手机APP的一般架构

很多手机APP的数据都是动态获取的,我们需要给APP提供接口,让APP请求接口获取数据。 不管你是开发NavtiveApp 还是 HybridApp, 都需要给APP提供接口。

传统的HybridApp 开发方式任然需要我们为APP开发一个接口程序, 我们还要用js写调用接口的ajax的代码。
如果使用TPM开发,不用特意写接口程序,也不用写ajax调用接口的程序 。 我们还是按照开发网站的方式开发手机客户端,在
Action中指派模板变量, 在模板中使用模板变量。 当我们将模板打包成APP时,APP能自动请求Action,然后渲染对应的模板,这时候请求Action时,Action会自动返回json格式数据。

3.其他手机开发的知识

我们要开发好手机APP,还需要了解更多手机开发的知识。 手机的尺寸大小不一样,所有我们的界面一般不能写成固定尺寸的, 要做响应式设计。 建议大家了解一下响应式设计的知识。 也可以结合一些UI框架,如bootstrap、purecss 他们自带对响应式的支持。
建议大家再阅读一下《移动端webapp开发必备知识》
http://www.qianduan.net/mobile-webapp-develop-essential-knowledge.html

二、环境搭建

首先你需要建立一个包含TPM的ThinkPHP项目。 你可以在ThinkPHP官方网站上下载TPM, 也可以中github中获得。 Github的地址是:
https://github.com/liu21st/extend/tree/master/Extend/Tool/TPM
将下载的文件中, Tpl目录下的文件复制到你的项目文件夹下Tpl目录中。将SwitchMobileTplBehavior.class.php 复制到 项目目录下 Lib/Behavior 目录下,将TemplateMobile.class.php 文件复制到 ThinkPHP/Extend/Driver/Template 下。
项目需要开启layout , 在项目配置文件中配置:

'LAYOUT_ON'=>true

在项目的Conf文件夹下建立tags.php ,代码为:

<&#63;php 
 return array( 
 'action_begin'=>array('SwitchMobileTpl')
 )

如果想手机客户端支持页面跳转,需要修改核心文件 ThinkPHP/Common/functions.php 中得redirect函数,修改为:

function redirect($url, $time=0, $msg='') {
  //多行URL地址支持
  $url    = str_replace(array("\n", "\r"), '', $url);
  if (empty($msg))
    $msg  = "系统将在{$time}秒之后自动跳转到{$url}!";
  if (!headers_sent()) {
    // redirect
    if (0 === $time) {
      //手机客户端跳转发送redirect的header
      if(defined('IS_CLIENT') && IS_CLIENT){
        if(''!==__APP__){
          $url=substr($url,strlen(__APP__));
        }
        header('redirect:'.$url);
      }else{
        header('Location: ' . $url);
      }
    } else {
      header("refresh:{$time};url={$url}");
      echo($msg);
    }
    exit();
  } else {
    $str  = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
    if ($time != 0)
      $str .= $msg;
    exit($str);
  }
 }

编辑器打开Tpl/index.html文件,修改代码

TPM.run("http://yourappurl"); 

将网址修改为你项目的真实访问地址。
然后,我们可将模板目录打包成手机APP 。
首先打开你的命令行, cd 到模板目录, 运行命令:

php build.php 

然后我们发现在模板目录会生成手机APP文件, 我们在手机上面安装即可。
命令行打包程序需要你的环境开启zip和curl扩展,如果不清楚的话请自行百度解决。
注意:打包命令需要联网,如果没有联网的话 可以用第三方打包工具例如phonegap打包。

打包命令还可以跟更多参数:
php build.php

参数说明:

platform :输入android或ios, 默认为android,现在还不支持IOS打包,大家敬请期待。
name :应用名称, 默认为TPM 。
package: 应用的包名,如:com.think.yourname ,一般为一个域名的倒序。 默认为 cn.thinkphp.tpm
version: 应用版本, 默认为1.0

三 使用说明

1.运行原理

之前我们在部署项目的时候发现ThinkPHP开启了layout,其实浏览器浏览网站时使用的layout文件是Tpl/layout.html, 而打包成手机APP后,layout文件其实是 Tpl/index.html , 我们用编辑器打开 Tpl/index.html文件, 发现里面多加载了一个js文件:TPM.js 。 在手机APP上运行时,TPM.js文件负责解析ThinkPHP模板标签和自动请求接口。
Tpl/index.html 中需要有这两个层:

<div id="main"></div>
 <div class="ajax_wait">正在加载中...</div>

TPM会把每次渲染模板的结果放到ID为main的层中。 class为ajax_wait的层 是在请求接口的时候会显示,我们可以在css文件中定义ajax_wait的样式。

2.模板标签

我们知道在手机APP中并没用PHP运行环境,解析ThinkPHP模板标签的是js,ThinkPHP的大部分模板标签都可以正常使用,但也有一些限制,比如模板标签中不能用PHP的函数,所以也不能在模板中使用U函数。
支持的ThinkPHP模板标签有: volist,foreach,for,empty,notempty,present,notpresent,eq,neq,heq,nheq,egt,gt,elt,lt,if,elseif,else,switch,case,default,in,notin,between,notbetween,include。

include标签在使用时有点限制,file属性必须写明控制器和方法,不能省略控制器。 如

<include file="Action:method" />

不能省略Action。如果有分组也不能省略分组。 其他标签的用法不变。

TPM未实现的标签有: defined,define等

TPM未实现 __URL__,__PUBLIC__,__ROOT__,__SELF__ 等模板替换变量。

大家需要在模板中写固定的URL , 以斜杠开头。URL地址格式为: /Action/method

3.独立手机APP的模板

我们如果希望网站模板和手机APP模板分离,可以定义项目配置:

'TPM_THEME'=>'mobile'

然后在Tpl目录下建立一个mobile文件夹。 在mobile文件夹中放置手机APP的模板。 这样如果是浏览器浏览网站首页,程序渲染的模板是Tpl/Index/index.html, 如果是手机APP打开,渲染的首页模板是 Tpl/mobile/Index/index.html .

4.配置说明

Tpl/index.html文件中需要加载TPM.js以及运行TPM , 运行TPM的代码是:

TPM.run(config)

TPM.run传递的config参数是配置项。 以对象形式传递。 可以设置的主要配置有:
api_base: 项目入口文件地址, http开头。
api_index: 首次请求的控制器方法,默认为/Index/index
下面举例说明一下这些配置项。
假设我们创建了一个项目, 入口文件的浏览地址是 http://www.xxx.com/index.php , 我们想手机APP打开的第一个页面不是首页,而是登陆页,登陆页的浏览地址假设是:
http://www.xxx.com/index.php/Index/login

那么TPM.run的传参如下:

TPM.run({
  api_base:'http://www.xxx.com/index.php',
  api_index:'/Index/login'
 });

如果你的项目做了隐藏入口文件的处理,那么api_base也可以不写入口文件,配置为:

TPM.run({
  api_base:'http://www.xxx.com',//注意,末尾不带斜杠
  api_index:'/Index/login'
 });

如果只想配置api_base这个参数,其他参数使用默认值,只传递一个网址作为参数:

TPM.run('http://www.xxx.com')


5.元素监听

我们做一些js效果,往往会监听元素事件,比如:

<script>
$(document).ready(function(){
  $('#id').click(function(){
  alert('click');
});
});
 <script>

这段代码监听一个元素的点击事件,但在TPM中这样监听可能会失效, 因为这种监听方式不能监听到新生的元素, 而TPM 的界面都是 请求接口渲染模板后新生的, 新生的内容会放在Tpl/index.html 文件中main层中。在TPM中要对这种新生的元素进行事件监听,可以使用TPM.ready,用法如下:

<script>
TPM.ready(function($){
$('#id').click(function(){
  alert('click');
});
});<script>

TPM还有很多特性,它不仅能和ThinkPHP结合, 也可以结合自己已有的接口。还有一些附件插件帮助我们实现一些常用功能。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software