Building Web Applications Using Parse Rest API

February 7, 2017 | Author: Luis Ramirez Coronado | Category: N/A
Share Embed Donate


Short Description

Download Building Web Applications Using Parse Rest API...

Description

Building Web Applications Using Parse REST API Using Laravel V4.x to build a simple blog Mhd Zaher Ghaibeh This book is for sale at http://leanpub.com/building-web-applications-using-parse-rest-api This version was published on 2015-01-10

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License

Tweet This Book! Please help Mhd Zaher Ghaibeh by spreading the word about this book on Twitter! The suggested tweet for this book is: I just bought the book Building Web Applications Using Parse REST API http://s.zah.me/1qWXTwX The suggested hashtag for this book is #laravelandparseit_english. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#laravelandparseit_english

Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1

Introduction . . . . . What Is Laravel . . What Is Parse Data? Now What? . . . .

. . . .

2 2 3 7

Creating Parse.com Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Types: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Your Classes: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9 9 9

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

User Authentication . . . . . . . . . . . . Setting Up The Database . . . . . . . . Creating The Migration File . . . . . . Creating The Seed File . . . . . . . . . Setting up the Layout template . . . . . Creating The Authentication Controller

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

14 14 14 17 19 19

Creating Posts Controller: . . . . . . . Configure Parse.com Library: . . . . . Testing Our Parse.com Configuration: Creating Admin Posts Controller: . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

23 23 24 24

Creating The Comments Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating The Comments Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building General Actions: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41 41 42

Putting everything together . . . Posts Missing functionality . . . Comments Missing functionality Front-end Functionality . . . . . getPost Function . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

54 54 56 64 67

Refactoring the posts controller, to use Models Create the Posts Model Class . . . . . . . . . . Create getPosts Function . . . . . . . . . . . . Create getPost Function . . . . . . . . . . . . . Creating deleteItem Function . . . . . . . . . . Create handleItem Function . . . . . . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

70 70 72 74 77 78

CONTENTS

Refactoring the comments controller, to use Models The Comments Model Class . . . . . . . . . . . . . getComments Function . . . . . . . . . . . . . . . . getComment Function . . . . . . . . . . . . . . . . getPostComments Function . . . . . . . . . . . . . . deleteItem Function . . . . . . . . . . . . . . . . . . handleItem Function . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

83 83 83 85 86 87 87

Mastering Parse Query Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How to use parse query class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

91 91

Learning Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . More about Parse Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . More about Laravel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

98 98 98

Preparing your production server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Your Laravel & nginx Server . . . . . . . . . . . . . . . . . . . . . . . . . . .

99 99

Final Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Foreword by Mhd Zaher Ghaibeh First of all I have to say thanks for everyone who encourage me to start this small journey and type this beginners book, about how to use and benefit from Parse on your next web project, and I should also say thank for Boydlee Pollentine¹ who encourage me to read about Parse, and know how to use it with web applications, not only for mobiles, and also to my oldest friend Hala Deeb² who always encourage me to not limit my imagination.

Who Am I? I am the Co-founder of Creative Web Group Syria³, a web development startup that specializes in developing modern web applications and utilizing the latest web development technologies and methodologies. I have 8 years of web development experience and holds a Bachelor Of Information Technology from the Syrian University, Damascus. I am currently working with Tipsy & Tumbler Limited⁴ as Lead developer.

Thank You I want also to thank you, for supporting this small project by purchasing the book, and I would like to encourage you contacting me via email if you find any errors, or you have any question don’t hesitate to contact me and start a discussion about it, or to say Hi.

Contact Info Name : Mhd Zaher Ghaibeh Email : [email protected]⁵ Blog : http://www.zah.me⁶ / Arabic Blog ¹http://boydlee.com/ ²http://www.haladeeb.name/ ³http://creativewebgroup-sy.com/ ⁴http://www.tipsyandtumbler.co.uk/ ⁵[email protected] ⁶http://www.zah.me

Introduction What Is Laravel Quoting from Laravel Documentation⁷: Laravel Philosophy Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we’ve attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked. To simplify the idea, Laravel is a powerful web application framework, which will help you to create your next web application in an elegant powerful way.

Laravel Features • • • • • •

RESTful Routing. Powerful Template Engine (called Blade). Proven Foundation, since it has been built on top of many Symfony2⁸ Components. Great ORM and Migration System, to deal with the database. Supporting many Databases including : MySQL, SQLite, MSSQL, and Postgresql. Composer powered, so that you can use Composer to install third party libraries which you can search for on Packagist⁹. • Built with testing in mind. • Great Community. ⁷http://laravel.com/docs ⁸http://www.symfony.com ⁹http://packagist.org

3

Introduction

Please Note: This book is not intended to teach you Laravel, this book is going to demonstrate how you can use and interact with Parse Data¹⁰ from Parse.com¹¹. If your looking for a resources to learn Laravel 4, you can check Dayle Rees¹² book Code Bright¹³.

Installing Laravel 4 There are so many ways to install Laravel, the one which I really like is to go to Laravel website¹⁴, download the latest version and extract it on your computer, Open up terminal if you’re on a Mac or Command Prompt if you’re using Windows, navigate to the directory where you have extracted your files and then issue the command: composer install

to install all the required libraries, including Laravel itself. But also you can do it like this : • Download and install composer from http://www.getcomopser.org¹⁵. • From the terminal issue the command : composer create-project laravel/laravel jasmine --prefer-dist

• Configure your Apache virtual host to handle the domains. If you don’t know how to do that, click here¹⁶ (I will use jasmine.dev here to reference to the blog app). • Change the permission for storage directory to be 777 and ensure that you choose to recursively give all directories within it the same permissions.

What Is Parse Data? Quoting from Parse.com¹⁷ website: Save flexible data objects to the cloud with SDKs for every platform. No servers necessary. So in easy words, you can use Parse Data as your database server, which you can interact with to save and retrieve your data whenever you need it. ¹⁰https://parse.com/products/data#howitworks ¹¹https://parse.com/ ¹²https://twitter.com/daylerees ¹³https://leanpub.com/codebright ¹⁴http://laravel.com ¹⁵http://www.getcomopser.org ¹⁶http://httpd.apache.org/docs/2.2/vhosts/examples.html ¹⁷http://www.parse.com/products/data

4

Introduction

Why Using Parse.com There is not just one reason to use Parse.com, there are many of them, a small introduction can’t describe the full potential use of Parse Data¹⁸, but i can say that your limitation is your imagination. So I will list some of the features which you can get when using Parse products¹⁹. • We can host our static image files (up to 10MB per file) on Parse Hosting²⁰ Service, this way you will be using Parse CDN to serve the images of your site. • We can use Parse Analytics²¹ Service to track our API real-time usage, and to track our custom events via the dashboard. • Offload User management, Quickly add user accounts to your app without having to code a full authentication system yourself. • Easy Scalability and extendability by simply adding new feature for your application, for example you can use Parse Social²² to easily integrate your application with Facebook and Twitter, which You can take a look at Parse Customers²³ page to get around and see what other developers has been using Parse Products²⁴ for.

Parse.com Data Features • Full Stack Of SDK, which you can use to interact with your data. • Powerful Data Management, which you can use to manage, search, and update your content without writing a single line of code.

Data Browser

• Advanced filtering directly from within the data browser. ¹⁸https://www.parse.com/products/data ¹⁹https://www.parse.com/products/ ²⁰https://www.parse.com/products/hosting ²¹https://www.parse.com/products/analytics ²²https://www.parse.com/products/social ²³https://www.parse.com/customers/featured ²⁴https://www.parse.com/products

5

Introduction

Data Filtering

• Ability to interact with other Parse.com²⁵ products.

Signup With Parse.com Since we are going to use Parse Data²⁶ as our database backend, we need to have an account with them, and create an app to have your own key which you will use for interacting with Parse.com securely. To do this, you need to: 1. Go to Parse.com Signup page²⁷. 2. After you finish you will be redirected to your Dashboard and you will be greeting with this nice box, which asks you to create your first app:

Create a new app box

1. Now lets create our new app and let’s call jasmine. ²⁵http://parse.com/products/ ²⁶http://www.parse.com ²⁷https://parse.com/#signup

6

Introduction

2. After you click the create button, you will have a small window, which will contain all your keys which you will use to interact with Parse.com.

Your application API keys

as you can see you have many keys, and lets be honest, all you want to have is only : 1. 2. 3. 4.

Application ID. Client Key. REST API Key. Master Key.

and now we are ready to go, just remember to save them for you only, and not publish them on the web, otherwise people will be able to access your data.

7

Introduction

Now What? Let’s see, we have installed Laravel 4, we have created an account on Parse.com, what else do we need? Actually we are missing just one component, which is the ‘PHP Parse.com Library. Sadly, Parse.com does not have such library, but that hasn’t stopped apotropaic²⁸ from creating one, Considering this is the only library recommended by Parse.com website https://parse.com/docs/api_libraries²⁹, this is what we are going to use, and we might modify it if we find anything we need to change or enhance.

How to install parse.com-php-library The easiest way to install the library is by downloading it to our app directory, and adding it to composer auto load so lets do that: Why not clone it via git? It would be nice to do so, but what if you have modified the code of the library? Next time the library was updated, you will lose your modifications.

• Download the library from apotropaic³⁰ github repo. • Extract the library in app/libraries/parse directory. • Edit composer.json so its look like :

"autoload": { "classmap": [ "app/commands", "app/controllers", "app/models", "app/database/migrations", "app/database/seeds", "app/libraries/parse", "app/tests/TestCase.php" ], },

• Last thing you have to issue is the composer command :

²⁸https://github.com/apotropaic/parse.com-php-library ²⁹https://parse.com/docs/api_libraries ³⁰https://github.com/apotropaic/parse.com-php-library

Introduction

8

composer dump-autoload

and that’s it, we are done. In the next chapter, we are going to create the Parse.com Classes which will be used by our blog to store our posts & comments on it .

Creating Parse.com Data Classes Data Types: To create the class, we need first to know the types of data which is available in Parse.com Data. Here is a list with all of the data types within Parse.com Data: 1. Date: The Date type contains a field iso which contains a UTC timestamp stored in ISO 8601 format with millisecond precision: YYYY-MM-DDTHH:MM:SS.MMMZ. 2. Bytes: The Bytes type contains a field base64 which contains a base64 encoding of binary data. The specific base64 encoding is the one used by MIME, and does not contain whitespace. 3. Pointer: The Pointer type is used when we set a ParseObject as the value of another object. It contains the className and objectId of the referred-to value. 4. Relation: The Relation type is used for many-to-many relations when we use ParseRelation as a value. It has a className that is the class name of the target objects. 5. String. 6. Number. 7. Boolean: Simple, true/false value. 8. File: You can upload files and add use the hosting service which is offered by Parse.com Hosting, in the free account you will have 1GB to upload your files to, but keep in mind that the file should not exceed 10MB in size. 9. GeoPoint: The GeoPoint type is used with maps and geolocation data, so it will contain the latitude and longitude values for the point. 10. Array. 11. Object: A hashed array as JSON format.

Creating Your Classes: Posts Class: Now that we have know all the types of data which we can use within our class, let’s create our Posts class, this class will hold all of our blog posts. Please Note, Before we start with the operation, lets try to simplify the idea of the classes for those who never worked with NOSQL before, and to be honest the simplest way for me to describe it, is that the Class represent the Table in any RDMS, and the row record in RDMS is simply the equivalent for Object in Parse.com Data. So whenever we say lets get the object id, or lets get the object, make sure that you translate it in your mind like lets get the row id, or lets get the row record.

10

Creating Parse.com Data Classes

First of all, lets go to Parse.com³¹ and login to the dashboard, because we are going to use the data browser to create our first class.

Parse.com Dashboard - Data Browser

To create our first class, we simply click on the top left blue button which say New Class, and that will prompt us to enter the name of the class which you want to create.

New Class Prompt

To name our class, we should make sure to use only numbers, letters, and underscore, and to only begin with a letter. Now that we have created our class, we should create the tables which will be contained within the class. Let’s have a few minutes to think, what should the class have as a columns ? Now that we have taken few minutes to think, We have found that we will need those columns: 1. 2. 3. 4. 5.

Post title, and it will be of the type String. Post body, and it will be of the type String. Post date, and it will be of the type Date. Post update, and it will be of the type Date. Post active, and it will be of the type Boolean, and it will indicate if this post is published or not.

³¹http://parse.com

11

Creating Parse.com Data Classes

So after we have defined what we want, let’s see how we can create each columns. First we click on the class name, then we click on the + Col button from the buttons bar.

The buttons bar

Once we click it we will be prompt with a nice modal to type the name of the column and select the type of the column from the data types which we have talked about earlier.

Create new column

In the column name we type title since this is the first column which we will use to hold the title of our post, then we select the type String, because it will holds only string. We will create the same thing for each of the other fields. But wait a minute, did I mention that Parse.com data already have some default columns which we can use? Whenever you create a new class Parse.com automatically adds the following column to the class: • objectId: This will hold the id of the object (the id of the record) which we will use, and it will be generated for you automatically so don’t worry about it. • createdAt: This is going to be date data type column which represent the date/time which you create your record. • updatedAt: This is going to be date data type column which represent the date/time which you update your record, but by default when you create a record, it will have the same value as createdAt.

12

Creating Parse.com Data Classes

So after this small info, you know that you only need to create the body and the active field. Name of the column The name of the column, Must only contain alphanumeric or underscore characters, and must begin with a letter or number.

After you finish, you should see something like the image below:

Posts Class

To make things bit interesting, why don’t you try to click on the + Row button and try to add the value of each column directly using the Data Browser, you will notice how much easy it is to edit/add new value using the data browser. After you finish, you will have something like the image below:

Posts class with some data

By default, the default value for the boolean when you add it is true, for now let’s choose to set it to false. Undefined Value By default, you can have one or all of your custom columns to have value, but this is not a mandatory thing, I mean for example here, you can have a body for the post, but your not required to have a title and when you retrieve the data, you will not get any title field and thats what they mean by undefined. Remember - you don’t have control over the default fields such as objectId, createdAt and updatedAt.

Comments Class: Now that we’ve become familiar with the Data browser, I don’t think we need to get more into how to create the Comments Class, since its the same old story. Lets define what is the fields which we are going to use: • Author name: a String which will hold the name of the comment author. • Author email: a String also and it will hold the email of the comment author. • Comment body: yes, you guess it right, its also a String, which will hold the full comment.

13

Creating Parse.com Data Classes

• Approved: boolean type, which will indicate that the comment is approved by the blog author or not. • Post: this one is a new one, we didn’t use any like it in the Posts class, this is going to be a Pointer, which will point to the the Post which the comment belong to (you can think of it as the Foreign Key which point to the post).

Creating a pointer field

Creating a pointer field

Please don’t stop here, go ahead and add some default data to the comment class, but make sure that you choose false for the approved field for now. Adding a pointer via Data Browser: Just so that you know, when you add a pointer you will not be able to select it. Instead, you can simple copy the objectId of the record which we want to use, and just paste it in the field.

Comment class with some data

User Authentication Setting Up The Database To setup the database in Laravel 4, all you have to do it to edit the file database.php which located at: app/config/database.php

As you have read about Laravel currently it support : • • • •

SQLite. MySQL. Postgresql. SQL Server.

So when you open it you will have to change the default connection to sqlite, to match the following code: return array( 'fetch' => PDO::FETCH_CLASS, 'default' => 'sqlite', 'connections' => array( 'sqlite' => array( 'driver' => 'sqlite', 'database' => __DIR__.'/../database/production.sqlite', 'prefix' => '', ), ), );

I have removed all the comments from the code, so all you have to change is the default value to become sqlite.

Creating The Migration File Now we need to create the migration file which will be used to track our database schema. Open your terminal and navigate to your larval directory and type the following command:

User Authentication

15

php artisan migrate:make --table=users CreateUsersTable

so the result will be something like : Created Migration: 2013_09_14_154114_CreateUsersTable Generating optimized class loader Compiling common classes

Note: The name of the file 2013-09-14-154114-CreateUsersTable.php should be different than the one you will have cause it will use the current date and time for the execution time, and as you can see am executing the command on 14/09/2013 at 15:41:14

Now lets open that file which you will find under the migrations directory under the database directory : app/database/migrations/2013_09_14_154114_CreateUsersTable.php
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF