How to implement sending JSON in CakePHP - php

I have to create web page for testing and I don't know how to implement it's logic (because I don't want to break MVC). It will be created in CakePHP.
Base thing I want to do is, that presenters action will have a parameter (JSON object or JSON string) and based on this parameter, there will be created a testing form inside view.
After user submits the answer, it will be sent to my PHP algorithm as a parameter(type of JSON object or string). This algorithm will return another JSON object that will be used as parameter for above mentioned presenters action.
I don't know how to implement this logic of sending and receiving JSON in order of not breaking MVC rules. Please explain it to me.

The first thing to do is think about your design.
The controller can process your data and return a JSON response, so you'll want to use that. Luckily Cake has this built in. Have a read of the book, http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
If you are passing JSON into your controller, you'll want to just pick it up out of the request. You'll be able to find it by debugging the request inside your controller. debug($this->request).
Then you can process the JSON in your controller, do some stuff and return a JSON response.

Related

Passing an array of values into Rest API Route

I am using Slim framework to create an REST API for my project. The WebApp itself is developed using ReactJS.
I have a doubt regarding the same. I have a set of values stored in an array in my ReactJS App. These values are filters which is used ti filter data from my table.
My table contains a field called location. In my WebApp I have search filter were I can add multiple locations based on which the results have to be displayed. I store these filters in an array.
I want to know how can I pass this array to Rest API Route so that I can get this array in my REST API Framework.
I want to achieve something like
/routes/location/[arrayOfValues]
There are only two ways of passing data to the server - either as URL params (for POST, GET, or anything else) or in the request body (for PUT or POST). Are you also writing the code to handle the API request? From your description of the use case, it sounds like GET would be the most semantically correct verb, so you you should use URL params as #BrianPutt suggested. Using square brackets is the standard way to encode an array value. How are the locations defined? Longitude/latitude? If so, you could also just build a comma-separated string, e.g.
/routes/location?q=12.3409,-40.0004,2.34004,120.0294
But odds are your back end framework has built-in support for parsing those URL params, so you should just use that.
/routes/location?q[]=12.3409,-40.0004&q[]=2.34004,120.0294
The only reason not to do this is if you have a huge number of locations, in which case you might want to use a POST request and build some kind of JSON object to put in the body.
Also: be consistent! If the rest of your API uses JSON, you should probably use it here too.

Overriding route in Cakephp

I have one trouble in routing in CakePHP. I have index action of all customers. And the question is, is there a way to make it this way, when I go to /..../.../customers CakePhp renders index(as per default), but when I am going to /..../.../customers.json(in .json format), CakePhp renders another action, where some array is serialized. I already enabled mapping resources, so it works just fine without overriding, but is there some way I can implement this ?
I've already read https://book.cakephp.org/2.0/en/development/rest.html.
Thank you, Gransfall. I just check if the request is json and then load the view in the need way.
if(isset($this->request->params['ext'])){
if($this->request->params['ext']=='json'){
//here setting serialized array
}
}

REST api - Updating table with POST from view

I'm new to RESTful web services and still figuring out the design/architecture aspect coupled with MVC pattern. I am using Codeigniter framework to implement MVC.
I had a pretty simple question. I am using using form data to update a table in my database. I have written an api that will do this:
http://www.example.com/api/resource/tablename/?param1=info1...
Typical api. What I wanted to know was, in the MVC pattern should I be using cURL in my VIEW to POST data and update my table with the form data or should I still be send the POST data to my controller and make the api call from the controller to update the table.
To me it seems arbitrary at this point as both will accomplish the same thing but what is the standard practice? Is it okay to directly communicate with you api from the VIEW to update your db table??
Is it okay to directly communicate with you api from the VIEW to
update your db table??
Yes, it is...in fact that is pretty much what you should do in this case! Send your data directly to the API. Your API should do all data validation and return an error message (in a standardized format like JSON, XML etc) if any data validation fails OR perform whatever action it needs to do with the POSTed data. A great benefit in doing so would be that your API can be used by any caller and would be a complete ecosystem by itself.
Without knowing more about your intended applications I can say this:
Typically you want to try and keep any processing logic (PHP) out of your views if possible. The whole point of the controller is to handle transaction operations from your model and then pass it to your view. So if you are using an API to gather some data from a service that is intended to be used/manipulated in your view then the logical location for that would be in the controller.
The MVC pattern isn't a hard and fast law of X goes in Y and Y goes in Z. It is a pattern that makes it easy to extend and abstract your data gathering, processing logic, and visual layouts.
Technically depending on the application and how you planned to use it you could create a model for the API so that it could be used in multiple controllers without the need to re-write it.

What URL should Ajax call in an MVC project?

I'm a semi newbie so please bear with me... Note, I don't know either jQuery or Json at this point
In my MVC project (I'm not using a framework but the project combines a front controller with an MVC), I have:
1) a Controller, which sends some parameters to a DAO. The DAO runs a MySQL query and sends back to the Controller an array of articles.
2) a View layer where I want the user to be able to click a button to move from article to article. The way I'm proposing to do that is by a javascript Ajax call to get the next article in the array generated in the Controller.
My question is: what should be the URL called by the Ajax function? Obviously it cannot call the Controller (or can it?). Should I add a class of dedicated Ajax content vessels that the Controller would instantiate with the array? I have difficulties seeing how the View would find the right URL... Should the Controller pass the parameters to the View and let it request the query?
The XHR (also known as AJAX) calls are no different at controller level, then classical browser requests. The difference is only in what you expect to receive in response.
This means that, if you have fully realized views (no just dumb templates), the type of request should be important only to the views. You can easily distinguish them by adding extensions:
http://foo.in/user/list - simple request
http://foo.in/user/list.json - XHR request
The difference gets recognized mostly at the routing mechanism, which them sets specific details on the Request instance. When controller sees that Request instance has a isXHR flag, it tells the view: "Respond to this with something, that is not full HTML page".
Basically, the same controllers should handle both the normal and XHR calls. In fact, you do not care about, what type of request it is. Only whether you need to produce html, xml or json in the response.
P.S.: model layer should be completely unaffected by the type of requests.
From the list of above posts I assume you must know the Ajax syntax to call a method while editing articles.
How to do so is as follows:
1. Initially define an action inside your controller which servers your purpose (May be editing your articles in this context.)
2. Through ajax method specify the Controller and the action which you wants to call. (
At this juncture it should be Articles -- Controller, EditArticle -- Action).
The control automatically navigates to the particular action method.
Regards
Pavan.G
Depends on the framework you use. But generally:
You can use the Controller with sending a "flag" (in a GET variable for example), that it is a AJAX query, and then exit the function, but having different Controllers for AJAX queries are considered a nicer route :) Anyways, something similar to this:
function page() {
if($_GET["is_ajax"] == "1") {
// return the AJAX query
return;
}
// go on with showing the page
}
Hope this helps!

what's the best way to integrate dataTables with cakePhp using the MVC approach

I've done up a bit of code in which I attempt to integrate data tables (http://datatables.net/) with cakePHP.
It's up and running with my own app, but I want to make it more generic, so it can be used by anyone across any cakePhp application, and most importantly I want it to fit in with cakePHP conventions.
So at the moment this is what I have...
A cakePHP helper called dataTables, which takes the following arguments: $modelName, $fields, $headers.
$modelName is the name of the model whose data will be populating the table.
$fields is an array of fields we want to show in the table (all fields must be prepended with "ModelName." which means we can show associated model values in the table)
$headers is a list of headers we want to be displayed at the top of the table.
The helper produces an empty html table (with the $headers as headers). The table is then populated by datables' javascript (you might have to read up on this if you're not familiar with dataTables server-side processing).
The Javascript retrieves the table data from the dataTable() action of the controller whose model we want to get at. The javascript will also send the model name (which we sent to the helper), and the fields. The controller then prints out the JSON data (through a blank view)
My two main questions are:
It doesn't seem right to place the dataTable action in a controller. A) because it doesn't actually need the controller because it knows what model and fields it needs to load and B) because it's not really a user action, its really just a JSON response. So where should it be put?
To print the JSON repsonse for my dataTable() action, I use a "blank.ctp" view and the use echo jsonencode($output). It doesn't seem right to use a view to output JSON data. Usually views are just for the user right?
One way of answering both of these questions is to have a standalone dataTable.php file, which will print the relevant JSON data based on the model name and fields it receives.
But this ^^ doesn't seem logical considering the MVC pattern.
The code is a bit messy at the moment (answers to the above should help me tidy it up!) but let me know if need to see.
Hope this makes sense to someone other then myself..
I thought about this for a second and a plugin seems to be the best idea.
You can use a Component to load the helper automatically and give you a controller visible hook to set the data for the helper/element that provides the output.
Use a behavior to expose the model function for your json, and then use the component to set the data.
As far as whether or not you should use a view or not - here is the section from the book on json views.
The _serialize key is a special view variable that indicates which
other view variable(s) should be serialized when using a data view.
This lets you skip defining view files for your controller actions if
you don’t need to do any custom formatting before your data is
converted into json/xml.
If you need to do any formatting or manipulation of your view
variables before generating the response, you should use view files.
The value of _serialize can be either a string or an array of view
variables to serialize:
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#using-data-views-with-the-serialize-key
I wrote a CakePHP Componenent that handles this https://github.com/cnizzdotcom/cakephp-datatable

Categories