PHP
Article

Mobile App Development with Zend Studio

By Daniel Berman

The world has turned mobile. This is not new, and it should therefore be no surprise to anyone that the results of the 2015 DevPulse survey by Zend show that a vast majority of PHP developers are working on, or intend to work on, mobile apps.

Mobile app development poses many challenges for developers, one of which is tying in the front end of the mobile application with the back-end web service APIs.

This tutorial describes how to simultaneously create, test and modify both the front and back end of a modern mobile app using Zend Studio’s mobile development features.

Zend Studio Logo

The steps described in this article were performed using Zend Studio 12.5 and a Zend Server 8 AWS instance. You can, of course, use any PHP server of your choice, local or remote, to host the API project.

Step 1: Creating a Cloud Connected Mobile Project

Your first step is to create a new Cloud Connected Mobile (CCM) project in your Zend Studio workspace.
A CCM project contains both a hybrid mobile project defining the front-end of your mobile app and a project containing all the back-end APIs.

  1. In Zend Studio’s menu-bar, go to File | New | Cloud Connected Mobile project.

    New CCM Project wizard

  2. In the New Cloud Connected Mobile Project wizard, enter a name for both the mobile client side project and the server-side project.

  3. In the PHP Server drop-down menu, select a PHP server, and then click Next.

    New CCM Project wizard

  4. In the next step of the wizard, you can select from one of the available project templates. Each contains a different code package with implementation examples. Read the descriptions for more info.
    In this tutorial, we’re going to go for the Simple Services template, which contains an example implementation of a REST service, and a client – side project consuming this service.

  5. Click Finish.

Two new projects appear in your workspace in the PHP Explorer.

CCM Project

Step 2: Previewing your App

Our next step is to preview our mobile app using the CordovaSim emulator supplied with Zend Studio. Obviously, since we just created the project, we will be previewing the sample code supplied with the template.

The CordovaSim mobile application simulator is a lightweight and fast emulator that allows you to preview your mobile application during and after development. It’s also an easy way to emulate native events (like for the accelerometer, geolocation, networking, etc.) using a GUI panel, which is important for mobile app testing.

To preview our mobile app, we will first need to deploy our server-side project containing the services it consumes.

  1. In the PHP Explorer, open the server-side project’s deployment.xml file. Tip: If there is no such file, simply right-click the server-side project, and select Configure | Add Application Deployment Support.

    deployment.xml

  2. In the Testing area, click Deploy application.

    Deploy Application dialog

  3. In the Deploy PHP Application dialog that pops up, select the server you wish to deploy to.

  4. Verify the application URL, and click Finish.
    The server-side project is deployed to the selected server.

  5. Right-click the project in the PHP Explorer, and select Run As | Run with CordovaSim.
    Your mobile application is opened in the CordovaSim emulator.

    CordovaSim Simulator

As you can see, the mobile app supplied with the template we chose for our CCM project is a very basic app that displays a list of customers with a button that retrieves the list. We will be developing this app later on in this tutorial.

Step 3 : Developing the Back-End APIs

Now, let’s focus on the server-side project.

The new server-side project we created is based on Apigility. Apigility is an API Builder that simplifies creating and maintaining useful, easy to consume and well structured APIs. If your mobile app has a back-end in the cloud serving data via REST API, Apigility should be your framework of choice.

Zend Studio’s integration with Apigility helps you create, document and test the APIs constructing the back-end of your applications within the same development environment. For more info on Apigility, click here.

In this tutorial, we will test and document the REST service supplied with the template using the Apigility editor built into Zend Studio’s mobile development support. The REST service, called ‘Customers’, handles the customer list of a company – retrieving the list from the database, adding new customers, etc.

  1. Open the Apigility editor by right-clicking the server-side project in the PHP Explorer, and selecting Open Apigility Editor.
    This will automatically start Apigility’s admin UI on a built-in PHP server and open the Apigility editor.

    Apigility Editor

  2. Click the ‘Customers’ service that is listed as a REST service under the MyCompany API.
    The REST Services page is displayed.

    REST Page

  3. The service already includes pre-defined settings, database settings, fields and controller files, all supplied with the template we selected.

  4. In the REST service header, click the yellow Test Service button.
    The Test Service view is displayed, and the URL field automatically contains the target, which is the IP (localhost) and a random port of the built-in PHP server. This server was started for the Apigility editor, together with the test method.

    Test Service

  5. Click the Test icon.
    Results are displayed in the Response window. You should receive a ‘200 OK’ response. If you receive a ‘404 Not Found’ response, make sure the URL at the top of the Test Service view is correct.

  6. Now let’s test the POST method for this service. In the Test Service view, enter the following values for the request parameters displayed in the Parameters table below the URL:

    • name – Daniel
    • location – Tel Aviv
    • activity – Coding
    • phone – 123456789
  7. Below the parameters table, change the request method to POST.

  8. Click the Test icon.
    Results are displayed in the Response window. You should receive a ‘201 Created’ response.

  9. Next, we’re going to document our API. Select the Documentation tab.

  10. Insert a description for the REST service and for the GET and POST methods. Something along the lines of:

    • REST service – Handles the company customers list
    • GET method – Retrieves the customers list
    • POST method – Adds a new customer to the list
  11. At the bottom of the page, click the Save button to save the documentation.

Your service is now documented!

There are plenty more aspects to Apigility than what is entailed in this tutorial. For example, Apigility will also help you build the authentication and authorization systems for your APIs. Check out Apigility’s docs to find out more.

Step 4: Developing the Front-End

Now that we’ve finished developing the back-end plumbing of our mobile app, let’s focus on improving the UI of our mobile app.

In this step, we will be adding a new page to our app, which will handle the process of submitting a new customer to our company’s customer list.

The front-end project created with the template we chose for our CCM project is based on jQueryMobile. Other template options include alternative frameworks such as Ionic, Bootstrap, etc.

I’ve included some code snippets to use throughout the steps, so let’s dive right into it.

Adding a New Page

As a first step, we’re going to add a new page to the UI with: input fields, a Submit button, a text area for response info from the server and a Back button for returning to the homepage of the app.

  1. From the PHP Explorer, open the mobile project’s ‘index.html’ file.

  2. At the end of the file, just before the BODY tag, enter the following code:

<div data-role="page" data-control-title="Add Customer" id="page3">
    <div data-theme="a" data-role="header">
        <a data-role="button" href="#page1" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
            Back
        </a>
        <h3>
            Add Customer
        </h3>
    </div>
    <div data-role="content">
        <div data-role="fieldcontain" data-controltype="textinput">
            <label for="name">
                Name
            </label>
            <input name="" id="name" placeholder="" value="" type="text">
        </div>
        <div data-role="fieldcontain" data-controltype="textinput">
            <label for="location">
                Location
            </label>
            <input name="" id="location" placeholder="" value="" type="text">
        </div>
        <div data-role="fieldcontain" data-controltype="textinput">
            <label for="activity">
                Activity
            </label>
            <input name="" id="activity" placeholder="" value="" type="text">
        </div>
        <div data-role="fieldcontain" data-controltype="textinput">
            <label for="phone">
                Phone
            </label>
            <input name="" id="phone" placeholder="" value="" type="text">
        </div>
        <a id="submit" data-role="button" href="#">
            Submit
        </a>
        <div data-role="fieldcontain" data-controltype="textarea">
            <label for="response">
                Response
            </label>
            <textarea name="" id="response" placeholder=""></textarea>
        </div>
    </div>
</div>

Adding a Button on the Entrypoint Page

Next, we’re going to add a button on the index/entry-point page of our mobile app that links to the newly created Add Customer page.

To do this, at the end of the DIV tag for the index page, on line 43 of the same index.html file, add the following code:

<a data-role="button" href="#page3">
    		Add Customer
	</a>

Binding the Submit Button to the API

What we’re going to do now is bind the Submit button we added to our new page to our APIs. Clicking the button will send a POST request to the server and result in a new customer added to the Customers list.

  1. In the PHP Explorer, open the my.js file located in the mobile project’s www/js folder.
  2. Locate the $(document).ready(function() { … } block (line 71), and insert the following code inside the block (line 75):

    $('#submit').bind('click', postCustomers);
  3. Then, add the implementation of the postCustomers() function. To do this, on line 70, add the following code:

    /**
    	 * Sends POST /customers[/:id] to API.
    	 */
    	function postCustomers() {
    		jQuery.mobile.showPageLoadingMsg('Loading');
    		$.ajax({
    			url : gatewayURL + '/customers',
    			cache : false,
    			type : 'POST',
    			contentType : 'application/json',
    			data : JSON.stringify({
    				'name' : $('#name').val(),
    				'location' : $('#location').val(),
    				'activity' : $('#activity').val(),
    				'phone' : $('#phone').val(),
    			}),
    			success : function(data, status, xhr) {
    				jQuery.mobile.hidePageLoadingMsg();
    				onPostCustomers(data);
    			},
    			error : function(xhr, status, errorThrown) {
    				jQuery.mobile.hidePageLoadingMsg();
    				onPostCustomers(xhr);
    			}
    		});
    	}
  4. And right after that, add the helper function on postCustomers() for handling the response from the POST request:

    /**
    * Shows POST /customers[/:id] response string in #response.
    *
    * @param response JSON object with response
    */
    function onPostCustomers(response) {
    	var raw = (typeof(response) == 'string') ? response : JSON.stringify(response);
    	$('#response').html(raw);
    }

Previewing our Changes

After saving the project, it’s time to preview our work. To do this, we’re going to use the CordovaSim simulator again.

Right-click on the project in the PHP Explorer, and select Run As | Run with CordovaSim.

CordovaSim Simulator

Give it a try and add a new customer!

To sum up, what we’ve done is added a new page to our mobile app and bound it to the server-side API.

Step 5: Testing as an Android Native App

Now that we’ve finished developing both the front and back end sides of our application, it’s time to pick it up a notch.

Zend Studio is integrated with Apache Cordova, the most popular and commonly used hybrid mobile development framework today. Amongst other features, this integration provides launchers for testing applications on native emulators and devices, and it also includes a series of generators that are capable of exporting native platform projects such as XCode or Android projects, and compiling them.

In the next two steps, we will be using these features to test our mobile app, as an Android native app, and export it, as a native application package.

Important! To run a mobile app on the Android emulator, and to export an APK file, there are some setup steps that have to be completed first. Namely, an Android SDK must be installed.

So, in Zend Studio’s PHP Explorer, right-click on the mobile project, and select Run As | Run on Android Emulator.
The Android Emulator is displayed with your mobile application open!

Android Emulator

Step 6: Exporting a Native Application Package

In this final step, we will export our mobile app as a native mobile application for the Android platform.

Zend Studio also allows you to export the project as a native project, which allows you to continue working on the project using native tools (e.g. Xcode for iOS).

  1. In the PHP Explorer, select the mobile application’s config.xml file.

    config.xml

  2. In the Export area, click Export Mobile Application.
    The Export Mobile Application dialog is displayed.

    config.xml

  3. Select the native platform you wish to export to – in this case Android.

  4. Select the destination folder for the application.
  5. Click Finish.

Zend Studio builds all the native binaries and our project is exported as an Android native application package (.apk).

Note: Since Zend Studio does not currently support signing of the exported application files, you have to sign them manually according to the respective platform guidelines, before submitting them in app stores.

What are you waiting for? Send it off to Google Play!

Summary

To sum it all up, Zend Studio allows mobile developers to seamlessly work on the back and front end of their mobile app, develop, test and manage new web services and go native, by exporting the project, as a native application package for Android, iOS or Windows Mobile.

Hope you enjoyed the ride!

  • stillatmylinux

    I’m getting stuck on step 2 adding a server. Here’s what I’m doing: http://stillatmylinux.com/adding-a-web-server-in-zend-studio-12/

  • Daniel Berman

    Sorry for the late reply. What Zend Server are you using?

    • stillatmylinux

      Version 8.0.2, Developer Standard Edition

      • Daniel Berman

        OK. Let’s try resetting deployment to your local Zend Server. Open the PHP servers view -> Right-click your server -> Edit -> Deployment -> Enable Zend Deployment (even if this is set, reset it and type the password again).

        • stillatmylinux

          That worked! The “enabled” checkbox wasn’t selected.

          • Daniel Berman

            Cool! You can ping me directly at daniel.be@zend.com or @proudboffin if you encounter any further issues! Which you will not of course! :-)

          • Daniel Berman

            Great! If you encounter any further issue, which you won’t :-), you can ping me directly at daniel.be@zend.com

  • optimisto1 .

    Hi, I wrote PHP Rest API, and working on mobile app using phonegap and Javascript. So first user login – it sends post request to login API. And the login API needs to persist some security token. So next time user needs to get a list of items, they need to send in that security token in the URL (get request) to REST API. So how to implement this security handshake? Thank you.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in PHP, once a week, for free.