Php with backbone js

Communication Between Backbone.js And PHP

Backbone.js is a Javascript framework known as MV* (Model, View and stuff). This framework has the Backbone.sync function to perform CRUD (Create, Read, Update, Delete) operations. In order for a model object to perform these operations, it should have a property named ‘url’. The ‘sync’ function receives 3 arguments: method, model and options. Model objects also have functions that call the ‘sync’ functions, these functions are: ‘fetch’, ‘save’ and ‘destroy’. The function Save does both Create and Update operation: If the property idAttribute is defined, and the idAttribute is set, ‘save’ sends an update request, otherwise it sends a ‘create’ request. The content type of the request is ”application/json”.

How Does The Server Know What Request Type It Receives?

The client-side developer specifies one ‘url’ only per model. The server-side program can determine the type by checking the value of $_SERVER[‘REQUEST_MOTHED’]:

  • ‘GET’ – a read (or fetch) request.
  • ‘POST’ – a create(save a new model) request.
  • ‘PUT’ – an update(save existing model’s detail) request.
  • ‘DELETE’ – a delete(destroy) request.

What To Send and How To Read?

Backbone.sync uses AJAX to send requests to the server. What you have to pass is the method and model. You better not skip the 3rd arguments, options, which contains at least two member:

  • ‘success’ – a function called when the server processes the request successfully.
  • ‘error’ – a function called when the server fails to process the request.
Читайте также:  Css класс по маске

// Recover or print an error message.

If you call Backbone.sync from an object don’t use ‘this” inside the success and error function as a reference to your object.

For example, if you call ‘sync’ from a view, write ‘myView=this;’ before your call to the ‘sync’ function.

Read Requests

If you send a ‘fetch’ request, specify ‘data’ in the ‘options’ argument, for example:

In the Server Side

The request attributes are taken from $_GET or $_REQUEST, as usual.

Save Requests

Send the attributes and the options.

In The Server Side

The data should be read from the file “php://input”, a filename used for reading data from the request body. The content is a string, and should be parsed, but since the incoming request data is JSON encoded, you should use the PHP method “json_decode”.

$post_vars = json_decode(file_get_contents(‘php://input’), true);

Destroy Requests

This time, you should set the ‘data’ member of the options argument to a JSON string. For example:

Backbone.sync(‘delete’, myModel, data: JSON.stringify(myModel), // This time the developer encodes the data.

success: function(model, resp)

In The Server Side

Read the data from ‘php://input’ and decode it using json_decode. For example:

$post_vars = json_decode(file_get_contents(‘php://input’), true);

Anyways …

You can make sure you read the data correctly by sending the contents of ‘$_SERVER’, $post_vars and ‘$_REQUEST’ to the error_log. To print an array use json_encode.

Sending a Response To the Client

The response is everything the server side application prints to the standard output. You should print your response data encoded into JSON, as follows:

Reading a Response

The response returned from the server is the first argument passed to the ‘succss’ callback function. It is not a model object, and you should get values from there using the method ‘get(attr-name’ or the member ‘attributes’.

To debug your code, you can use ‘alert(JSON.stringify(msg));’.

Источник

Backbone.js Как использовать с PHP

Я искал backbone.js, и я не могу понять, как заставить его общаться с php, чтобы сохранить данные моделей. Он отправляет запрос, но как я могу захватить этот запрос, будь то «Создать», «Обновить», «Прочитать», «Удалить» и т. Д.

Другим вариантом, который вы можете рассмотреть, является свертывание с предварительно упакованной структурой RESTful, которая имеет все необходимые функции, встроенные для выполнения запросов сервера Backbone. Мой личный фаворит – SlimPHP Framework Джоша Локхарта .

Некоторый простой пример кода (после установки SlimPHP), используемого для вызова ваших магистральных вызовов, выглядит следующим образом.

$app->get('/user', function() use ($app) < // See if session is set, get user info as array if (isset($_SESSION['userID']) < $user = // grab user with userID data from DB >// Respond to the get request with a json object $response = $app->response; $response['Content-Type'] = 'application/json'; $response->body(json_encode($user)); > 

Вот пример POST, который превращает Backbone json в массивы.

// Middleware that detects type of data and converts it to something usable $app->add('Slim_Middleware_ContentTypes'); // JSON to associative array . $app->post('/message', function() use ($app) < $dataIn = $app->request()->getBody(); . // Save to DB $dataIn['message'], $dataIn['author'], etc. > 

Вот пример PUT, использующий некоторые параметры.

$app->put('/user/:id', function($id) use ($app) < // Find appropriate user from DB that has $id as ID $dataIn = $app->request()->getBody(); // Save to DB $dataIn['name'], $dataIn['age'], etc. > 
$app->delete('/message/:id', function($id) use ($app) < // Find appropriate message from DB that has $id as ID // Delete message with id of $id > 

Хотя это не исчерпывающий пример всех других вещей, которые следует учитывать, он должен дать вам представление о тех типах открытых решений, которые уже существуют для вас. Мне лично нравится Slim, потому что он такой легкий, простой, но у него есть все функции, которые вы хотите использовать на сервере RESTful. Отлично подходит для прототипирования. Объедините его с уровнем абстракции DB и некоторыми другими инструментами, и вы можете сделать что угодно быстрее.

Здесь вы можете увидеть еще один пример кода:

И вот ссылка на некоторые другие RESTful-решения на основе PHP: список рамок

Модель backbone.js использует определенные URL для извлечения и отправки данных. Вы должны убедиться, что там есть скрипт php.

Теперь есть две возможности.

Во-первых, метод отправляется внутри переменной $ _POST в качестве дополнительной переменной. Во-вторых, вам нужно искать использованный метод запросов (GET, POST, PUT, DELETE), который вы можете использовать с $_SERVER[‘REQUEST_METHOD’]

Теперь вы можете использовать простые инструкции if-else или switch для обработки запроса и доставки необходимых данных, как я думаю, json.

$ GLOBALS [‘HTTP_RAW_POST_DATA’] отлично работает для меня, я не знаю, по какой причине print_r ($ _ POST) не печатает аффининга !!

В вашем php-скрипте вы будете иметь это для методов PUT и DELETE, поскольку вы можете отфильтровать их с помощью: $_SERVER[‘REQUEST_METHOD’]

parse_str(file_get_contents("php://input"),$post_vars); 

Если запрос POST или GET, вы можете использовать его нормально, но если запрос PUT или DELETE, используйте приведенную выше строку, и вы можете получить доступ к vars с помощью:

$post_vars['fruit'] for example. 

Когда вы будете готовы ответить на магистраль, вы должны сначала создать правильный заголовок:

header('Content-type: application/json; charset=utf-8'); 

и закодируйте ответ на json:

echo json_encode(array("message"=>"missing fields","status"=>200)); 

Источник

Php with backbone js

Assume that you have basic knowledge on php, backbone.js, underscore.js and jquery.
We will use Firefox browser with firebug to test.

Actually here we will learn how to use model, view and router of backbone.js and fetch data from server using php.

First of all we will create directory structure.

|-> php-backbone |-> js |-> jquery-2.0.3.min.js |-> underscore-min.js |-> backbone-min.js |-> api |-> example_1

create above directory structure in you web_root. and put those js files in js directory (those will be found in source, link at bottom or you can get those by google).

now we will create a Boilerplate in example_1 directory named “index.html”, so create a new index.html file under example_1 directory and write below code in this file.

Backbone’s only hard dependency is Underscore.js ( >= 1.5.0). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include jQuery, and json2.js for older Internet Explorer support. (Mimics of the Underscore and jQuery APIs, such as Lo-Dash and Zepto, will also tend to work, with varying degrees of compatibility.)

Now create an new example_1.js file in js directory, and include it at bottom of all script to our Boilerplate index.html file, then our index.html file will look like below.

and open it with you favorite editor.
In example_1.js, we will first create a “Message” model, and add a default property called “message” like below.

var MessageModel = Backbone.Model.extend( < defaults: < message: "Text Message" >>);

Now we will access our example_1 to test that is our model working or not. so url http://localhost/php-backbone/example_1/ on FireFox (this url for mine as i follow above directory structure so your url can not be like it, so use your url to access example_1). Open Firebug console, create a object of MessageModel and access its message property like below.

var msg = new MessageModel(); msg.get('message');

run this and will get output like below screenshot.

backbone.js, php

model default property access

After above model build backbone router like below.

var MessageRouter = Backbone.Router.extend(< routes:< "": "displayMessage" >, displayMessage: function() < var messageModel = new MessageModel(); console.log(messageModel.get("message")); >>); var messageRouter = new MessageRouter(); Backbone.history.start();

here we build a router and added a route and assigned a function “displayMessage”, in this function we created a model object for “MessageModel” and print its “message” property in console.
to execute this router we created object of this router. then we start backbone history to ask backbone to monitoring hashchange events, and dispatching routes.

Now if you access this example_1 from browser then you will see output “Text Message” on firebug console.

To create View, first we need to change our index.html under example_1 directory.
in body tag, we will add a div tag in which we will display our message, and a template which will use to contain message text. so add below html come in body tag before script tags.

here in template “” used to interpolate variable message.
So our template is ready, now we will create backbone view. add below code in example_1.js after model code.

var MessageView = Backbone.View.extend( < template:_.template($('#tpl-hello-backbone').html()), render:function (eventName) < $(this.el).html(this.template(this.model.toJSON())); return this; >>);

here we assigned javascript template and created render function which used to render the view template from model data.
Now we have to call this render function from router function “displayMessage”. change this function as below.

displayMessage: function() < var messageModel = new MessageModel(); var messageView = new MessageView(); $('#msg').html(messageView.render().el); >

here we created object of MessageView with our messageModel. and called view’s render function and put its output in our “#msg” div. there “el” is a DOM element which created from the view’s tagName, className, id and attributes properties, if specified. If not, el is an empty div.

Now if you access example_1 then you will see “Text Message” in browser.

Above we completed below steps::

1) Build directory structure
2) Created Boilerplate for backbone.js
3) Created backbone.js model
4) Created backbone.js router
5) Created backbone.js view

Now its time to get data from server (using php) and display it, we have already completed most of work, now we will just fetch data from server using our MessageModel.

Create “example_1.php” file in api directory and write one code in it like below.

here we just echo a string followed by json structure.

Then we need modify our model little bit that just add “urlRoot” property with vlaue “../api/example_1.php”, so change our model like below.

var MessageModel = Backbone.Model.extend( < urlRoot : '../api/example_1.php', defaults: < message: "Text Message" >>);

Then change the “displayMessage” function in backbone router like below.

displayMessage: function() < var messageModel = new MessageModel(); var messageView = new MessageView(); messageModel.fetch( < success: function () < $('#msg').html(messageView.render().el); >>); >

here we only use “messageModel.fetch()” function to collect data for this model from server. and after successful fetch we are calling render function. now if you access exmaple_1 then you can see output “Hello Backbonejs” in your browser.

if you can see this text then Congratulation 🙂 , if not then you can post comment, we will fix it together.

Источник

Оцените статью