Integration of Laravel (5.1) & Ember.js (1.13.0)

Source: Internet
Author: User
Tags php framework

Lavavel does not need to introduce too much, as the world's most popular PHP framework, with a clear architecture, perfect documentation, a wealth of tools and so on, can help developers quickly build multi-page Web applications.

However, with the development of technology, the other side of the Web program-the client, is becoming more and more meta (PC, mobile phone, tablet, other special equipment, etc.). Therefore, a unified mechanism is needed to facilitate communication between the server and different devices. The Restful API is based on this idea.

Nanyi gives a summary of the restful architecture:

  1. Each URI represents a resource;

  2. Between the client and the server, a presentation layer that transmits such resources;

  3. The client uses four HTTP verbs to operate the server-side resources to achieve "presentation-level state transformation".

In behavioral terms, the server interacts with different front-end devices through a unified API interface after agreeing on a set of resource interaction rules, based on this rule. The server only needs to focus on the storage and analysis of the data, or the implementation of the business logic. On different client side, its performance logic and interaction logic and server-side business logic realize the double separation--logical separation and physical separation.

If the front and back end only the resource (data) interaction, then the page routing naturally when the front-end control, equivalent to the front end of the first load page after the full page is no longer refreshed, all the data through Ajax from the backend with the use of, all the form submission is the same method, this is a single page application Page application, SPA).

Ember.js is a modular front-end framework, based on the MVC concept , which provides UI bindings, templating systems, and routing systems, which are ideal for rapid spa development. In particular, Ember also provides a complete command-line development package--ember Cli, which not only eliminates the tedious development environment configuration, but also provides rich development and build tools, for example, you can immediately develop with coffeescript or even ES6, The corresponding interpreter has been installed with the development package, in the case of starting Ember server, you do not have to change every time you type Ember build at the command line, the system automatically recognizes the text changes and interpretation and merging, the compiled files are placed in the dist/directory.

However, when I had Laravel and ember.js properly configured, I found that I could not immediately roll up my sleeves to write code because they were not born for each other. For example, I now face two problems:

  1. Laravel and Ember.js have their own routing system, how to let Laravel sell their own control of the URL?

  2. User authorization is usually managed and maintained by the server, Laravel provides a complete authentication scheme, but in the spa, the backend has to give a portion of the permissions to the front end (mainly page access rights and AJAX authorization), what is the best practice to solve this problem?

I believe that a lot of people have encountered similar problems before, the problem may have a general principle guidance, but at the operational level with the specific framework, confined to space, this article discusses the first question. The second question is answered separately.



Defining API Interfaces

In Laravel, the laravel/app/http/routes.php file is the entry for all URLs, and all URLs and corresponding handler functions should be defined here.

Laravel/app/http/routes.phproute::group (Array (' prefix ' = ' api/v1 '), function () {//USERS API ================    ================== route::get (' Users/{id} ', ' [email protected] ');    Route::d elete (' Users/{id} ', ' [email protected] ');    Route::p ut (' Users/{id} ', ' [email protected] ');    Route::p ost (' Users ', ' [email protected] '); Other API ==================================//...});

I put all the APIs into a routing group where the API request must be prefixed with the API/"version number", such as user information that requires the server to return id=5, and a GET request should be made to the following address:

Http://your_demain/api/v1/users/5

When the server receives the request, it passes the requests object to the GetById member method of the Usercontroller to do the processing.

I also defined the relevant interfaces for user authorization in the file and divided them into a group:

Laravel/app/http/routes.phproute::group (Array (' prefix ' = ' auth '), function () {Route::p ost (' Login ', ' Auth\[em    AIL protected] ');    Route::get (' logout ', ' auth\[email protected] '); Route::p ost (' register ', ' Auth\[email protected] ');});

Three interfaces provide login, logout and registration functions respectively.

Well, Laravel's routing just needs to do so many things.


Give control of the other URLs to the front end

Ember page starts with the ember/dist/index.html file as the portal, the Dist directory holds all the built files, which are automatically generated by the system. In the index.html file, 2 script files and 2 style files are loaded from the ember/dist/assets directory :

<!--ember/dist/index.html--><! DOCTYPE html>

These 4 files contain all the logic and style of the front end. Instead, Laravel takes laravel/public as the project root directory, which stores the front-end resources built by Laravel. So here's how I handle it:

  1. synchronize ember/dist/assets with laravel/public/assets two directories, the latter being the mirror of the former

  2. ? The laravel/resources/views defines a view named app.php, whose contents are  embe ? ?

  3. ? ? Laravel get the request except API and AUTH (hereafter referred to as non-API request), return app.php? ? ? ? ? ?

In normal use, the front end only makes non-API requests at the first load, and once the app.php front end gets control of the application's presentation layer, all interactions between the user and the app are captured and controlled by the front end as long as the page is not refreshed.

Here's how:

Because I do development under Windows, the system does not provide a direct synchronization of two local directory tools, but also did not find real-time automatic synchronization of third-party desktop applications, and finally selected a software named InSync, each synchronization requires a manual click, is a potential efficiency bottleneck.

Create the app.php file in the Laravel/resources/views directory and copy the contents of the ember/dist/index.html.

Create a new routing group in Laravel/app/http/routes.php:

Laravel/app/http/routes.phproute::get (' {data} ', function () {return View::make (' app ');}) ->where (' Data ', '. * ');

The group captures all non-API requests and returns app.php.


Front-end specific implementation

In Ember, each route has a model that is associated with it. The model is responsible for querying, changing, and saving the changes back to the server, which is done through the models adapter (Adapter). So you need to modify the adapter so that it matches the API prefix conventions defined by the backend:

Ember/app/adapters/application.jsexport default DS. Restadapter.extend ({namespace: ' Api/v1 '});

You can then define a front-end route in Ember/app/routers.js:

Ember/app/routers.jsrouter.map (function () {this.route (' user ', {path: '/user/:user_id '}); Other routes ...});

Here's a question you have to ask:

Each model in Ember can be regarded as a resource, and model has defined the various types of household behavior associated with such resources. For example, after I have defined the Usermodel, I want to query the server for a user record that can use the following code, which gives its network request (omitting the prefix):

This.store.find (' user ', 5); = = GET '/USERS/5 '

Create a new User:

var user = This.store.createRecord (' user ', {email: ' [email protected] ', Password: ' 123 '}); User.save (); = = POST to '/users '

This default behavior is not configurable, so the backend-provided API must be built with this rule, which is also a lack of flexibility with large frameworks. Lightweight front-end frameworks such as backbone are more competitive in applications that require a large number of customization capabilities.

Ember is aware of this problem, and in the latest version 2.0, it can be resolved with a custom service.


Summarize

At this point, determined the page loading scheme, opened the front and back of the data interchange channel, before and after the driven by fragmented into mutual cooperation, their respective roles, the application Finally "live" up.


Integration of Laravel (5.1) & Ember.js (1.13.0)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.