SoFunction
Updated on 2025-04-04

Brief tutorial on how to use ThinkPHP Mobile

1. Basic knowledge

1. Types of mobile apps

There are several mobile applications: WebApp, NativeApp, and HybridApp.

WebApp It is a mobile website that needs to be accessed using a mobile browser.

NativeAppIt is a mobile application developed in a native language and users need to download and install. The development cost of NativeApp is very high, and the development language of each platform is different. For example, the development language of IOS is object C, Android system APPs need to be developed in Java, and WindowsPhone needs to be developed in C#. So if we need to build an APP that can run on multiple platforms, we need to redevelop it multiple times in multiple languages.
Compared with NativeApp, WebApp development is much simpler. You can develop WebApps with html, css, and js, and it can be developed across multiple platforms at a time. However, WebApp requires users to open their mobile browser to enter the URL before accessing it, and it cannot be used to call the phone's camera, address book and other functions like NativeApp. WebApp's static resources such as html, css, js images are on the server. Users need to download it, which will consume more users' traffic. The static resources of NativeApp are local to the mobile phone.

HybridAppNeutralizes the respective advantages of NativeApp and WebApp. We can use html, css, js to develop, and it is compatible with multiple platforms. Users also need to download and install, and be able to call the phone's camera, address book and other functions. HybridApp's static resources are also local to the phone.

We know that ThinkPHP templates are also developed using HTML, CSS, and JS. So we wonder if we can directly package the ThinkPHP template into a mobile app? Let us open the computer version of the website, mobile version of the website and mobile APP at once, so the birth of TPM was born. TPM allows us to package ThinkPHP templates into a HybridApp.

2. General architecture of mobile app

The data of many mobile APPs is dynamically obtained. We need to provide an interface to the APP to allow the APP to request the interface to obtain data. Whether you are developing NavtiveApp or HybridApp, you need to provide an interface to the APP.

The traditional HybridApp development method still requires us to develop an interface program for the APP, and we also need to use js to write code to call the interface ajax.
If you use TPM to develop, you don’t need to write interface programs specifically, nor do you need to write programs that call interfaces with ajax. We still develop mobile client according to the method of developing websites.
Assign template variables in Action and use template variables in templates. When we package the template into an APP, the APP can automatically request Action and then render the corresponding template. When we request Action, the Action will automatically return json format data.

3. Knowledge about other mobile phone development

If we want to develop a mobile app well, we also need to know more about mobile phone development. The sizes of mobile phones are different. All our interfaces cannot be written as fixed sizes, and responsive designs are required. We recommend that you learn about responsive design. It can also be combined with some UI frameworks, such as bootstrap and purecss, which come with responsive support.
It is recommended that you read "Essential Knowledge on Mobile Webapp Development"
/

2. Environment construction

First you need to build a ThinkPHP project containing TPM. You can download TPM on the official ThinkPHP website, or you can get it in github. Github's address is:
/liu21st/extend/tree/master/Extend/Tool/TPM
Copy the files in the downloaded file and the Tpl directory to the Tpl directory in your project folder. Copy to the Lib/Behavior directory under the project directory, and copy the file to ThinkPHP/Extend/Driver/Template.
The project needs to enable layout and configure it in the project configuration file:

'LAYOUT_ON'=>true

Created in the Conf folder of the project, the code is:

<?php 
 return array( 
 'action_begin'=>array('SwitchMobileTpl')
 )

If you want the mobile client to support page redirect, you need to modify the redirect function in ThinkPHP/Common/ in the core file, and modify it to:

function redirect($url, $time=0, $msg='') {
  //Multi-line URL address support  $url    = str_replace(array("\n", "\r"), '', $url);
  if (empty($msg))
    $msg  = "The system will{$time}Automatically jump to{$url}!";
  if (!headers_sent()) {
    // redirect
    if (0 === $time) {
      //The mobile client jumps to send the redirect header      if(defined('IS_CLIENT') &amp;&amp; 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  = "&lt;meta http-equiv='Refresh' content='{$time};URL={$url}'&gt;";
    if ($time != 0)
      $str .= $msg;
    exit($str);
  }
 }

The editor opens Tpl/file and modifys the code

("http://yourappurl"); 

Modify the URL to the real access address of your project.
Then, we can package the template directory into a mobile app.
First open your command line, cd to the template directory, and run the command:

php  

Then we found that the mobile APP file will be generated in the template directory, and we can install it on the mobile phone.
The command line packaging program requires your environment to enable zip and curl extensions. If it is not clear, please solve it on Baidu.
Note: Packaging commands need to be connected to the Internet. If there is no Internet connection, you can use a third-party packaging tool such as phonegap.

Packaging commands can also be followed by more parameters:
php <platform> <name> <package> <version>

Parameter description:

platform : Enter android or ios, the default is Android, and IOS packaging is not supported yet, so please stay tuned.
name :The application name, defaults to TPM.
package:The application package name, such as:, is generally in reverse order of a domain name. Default is
version: Application version, default is 1.0

3. Instructions for use

1. Operation principle

Before, when we deployed the project, we found that ThinkPHP enabled layout. In fact, the layout file used by the browser to browse the website is Tpl/. After packaging it into a mobile APP, the layout file is actually Tpl/. We opened the Tpl/ file with the editor and found that there was an additional js file loading: . When running on mobile APP, the file is responsible for parsing ThinkPHP template tags and automatic request interfaces.
There are two layers in Tpl/:

&lt;div &gt;&lt;/div&gt;
 &lt;div class="ajax_wait"&gt;Loading...&lt;/div&gt;

TPM will place the result of each rendering of the template into the layer with ID main. The class is ajax_wait layer. It will be displayed when the interface is requested. We can define the style of ajax_wait in the css file.

2. Template tags

We know that the PHP running environment is not used in the mobile APP. The one who parses the ThinkPHP template tag is js. Most of the ThinkPHP template tags can be used normally, but there are some restrictions. For example, the PHP function cannot be used in the template tag, so the U function cannot be used in the template.
The supported ThinkPHP template tags are: voltage, foreach, for,empty,notepty,present,notpresent,eq,neq,heq,nheq,egt,gt,elt,lt,if,elseif,else,switch,case,default,in,notin,between,notween,include.

The include tag is somewhat restricted when used. The file attribute must state the controller and method, and the controller cannot be omitted. like

<include file="Action:method" />

Action cannot be omitted. If there is a group, the grouping cannot be omitted. The usage of other tags remains unchanged.

The tags not implemented by TPM are: defined, defined, etc.

TPM does not implement template replacement variables such as __URL__, __PUBLIC__, __ROOT__, __SELF__, etc.

Everyone needs to write a fixed URL in the template, starting with a slash. The URL address format is: /Action/method

3. Template for independent mobile apps

If we want the website template and mobile APP template to be separated, we can define the project configuration:

'TPM_THEME'=>'mobile'

Then create a mobile folder in the Tpl directory. Place the template for the mobile app in the mobile folder. In this way, if the browser is browsing the home page of the website, the template rendered by the program is Tpl/Index/. If the mobile APP is opened, the home page template rendered is Tpl/mobile/Index/.

4. Configuration instructions

TPL/file needs to be loaded and run TPM. The code to run TPM is:

(config)

The passed config parameter is the configuration item. Passed as an object. The main configurations that can be set are:
api_base:The project entrance file address, beginning with http.
api_index:The controller method requested for the first time, default is /Index/index
Here are some examples of these configuration items.
Suppose we create a project, and the browsing address of the entrance file is /. We think the first page opened by the mobile APP is not the home page, but the login page. The browsing address of the login page is assuming:
//Index/login

Then the transmission parameters are as follows:

({
  api_base:'/',
  api_index:'/Index/login'
 });

If your project has been processed to hide the entry file, then api_base can also not write the entry file and be configured as:

({
  api_base:'',//Note that there is no slash at the end  api_index:'/Index/login'
 });

If you only want to configure the api_base parameter, other parameters use the default value, and only pass one URL as the parameter:

('')


5. Element monitoring

We do some js effects and often listen to element events, such as:

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

This code monitors the click event of an element, but it may be invalid in TPM because this listening method cannot monitor new elements. The interface of TPM is reborn after the interface is requested to render the template, and the reborn content will be placed in the main layer in the Tpl/ file. In TPM, you need to listen for event on this new element, which can be used, and the usage is as follows:

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

TPM also has many features, which can not only be combined with ThinkPHP, but also combine it with its own existing interfaces. There are also some attachments and plug-ins that help us implement some common functions.