Backbone JS and CodeIgniter REST Server - codeigniter

I have a standard CI web app, but I've decided to get the chaotic javascript in order using backbone. I had a whole pile of serialized forms/jQuery AJAX requests to various controller methods: authenticate, change_password, register_member, request_new_password, etc.., and don't quite understand how REST works instead. I'm using Phil Sturgeon's REST library for CI https://github.com/philsturgeon/codeigniter-restserver
Should every backbone model have a different api url? And what am I supposed to actually call the controller methods?
<?php
require(APPPATH.'/libraries/REST_Controller.php');
class RestApi extends REST_Controller
{
function get()
{
But it just 404s.
I just don't get how to replace the routing to fifty of my old methods based on a handful of HTTP methods. Does the name of the backbone model need to match something on the server side?

You have to name your functions index_HTTPMETHOD. In your example it would be:
class RestApi extends REST_Controller {
// this will handle GET http://.../RestApi
function index_get() {
}
// additionally this will handle POST http://.../RestApi
function index_post() {
}
// and so forth
// if you want to POST to http://.../RestApi/somefunc
function somefunc_post() {
}
}

the url-attribute of the model should match the server-side 'url' which returns the JSON that will make up the model's attributes. Backbone.js has default functionality to this, which is to match the model's collection url with it's id attribute. The collection url requirement can be foregone by overriding the urlRoot -function, in order to operate model's outside of collections.
If you want to be independent of the id -attribute as well, you sould override the url -attribute/function to provide your own url that matches to the model on the server, like this:
url: 'path/to/my/model'
or
url: function() { // Define the url as a function of some model properties
var path = this.model_root + '/' + 'some_other_url_fragment/' + this.chosen_model_identifier;
return path;
}

Related

how to prepare api using laravel and vue.js

good day;
I am new in vue.js and I want to build API in my project using vue.js and laravel
I have some question and answer because I got confused
I have services controller that return all service
as below:-
class ServicesController extends Controller
{
public function Services()
{
//get all serveice
$services=Services::where(['deleted'=>1,'status'=>1])->get();
return response()->json($services);
}
}
and API route as below:-
Route::get('/Servicess', 'API\ServicesController#Services');
it is necessary to make a component to send a request to using
Axios request to get data and if yes how to tell the mobile developer about a link to access it.
i want the steps from vue.js side to
prepare data and send it using Axios
You can not use your front-end javascript code inside php controllers, there are two ways to use the data; First: send it via the request. Second: fetch the required data at the back-end side and use it there.
Also there are many alternatives to Axios like the fetch api etc.
Update#1:
example controller
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function exampleMethod(Request $request){
$name = $request->input('name');
//DO sth
}
}
Route in api.php:
Route::get('/users', 'API\ExampleController#exampleMethod');

How to map different HTTP methods on the same url to different controllers?

I have my API for a small part of my application split over two controllers, because of (external) requirements on the casing of JSON data in the API (some requests should use camelCasing, while others should use PascalCasing).
Now, I have a url that I want to map with PascalCasing for GET, but camelCasing for PUT, so I tried the following:
[PascalCasing] // custom attribute, part of our code
// We configure all controllers that *don't* have this to use
// camelCasing
public class PascalCasedController : ApiController
{
[HttpGet]
[Route("url/to/my/resource/{id}")]
public IHttpActionResult(int id)
{
return Ok(GetResource(id));
}
}
public class CamelCasedController : ApiController
{
[HttpPut]
[Route("url/to/my/resource/{id}")]
public IHttpActionResult(int id, Resource resource)
{
SaveResource(id, resource);
return Ok();
}
}
The GET request works as expected, but if I try to PUT something there with Fiddler, I get the following error message:
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
The request has found the following matching controller types:
MyProject.PascalCaseController
MyProject.CamelCaseController
I realize this is probably because WebAPI maps routes to controllers first and actions next, but if HTTP methods are considered, there really isn't any ambiguity here. Is there any way that I can tell WebAPI how to do this, without having to have the methods in the same controller?
#Tomas - There's an interface "System.Web.Http.Dispatcher.IHttpControllerSelector" exposed in System.Web.Http assembly. You can use that interface and create your own HttpControllerSelector. You can then replace the DefaultControllerSelector with your custom controller selector in the HttpConfiguration during AreaRegistration.
httpConfig.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(services.GetHttpControllerSelector()));
In this custom controller selector you can write your own implementation of SelectController() method of IHttpControllerSelector in which you can call GetControllerMapping() method of IHttpControllerSelector. This will give you the list of all the controllers registered. For every controller you can check for the DeclaredMethods and check for the CustomAttributes for each of the DeclaredMethods. In your case it will be either HttpGetAttribute or HttpPutAttribute.
Check the Method type of the incoming HttpRequestMessage (GET/PUT) and compare it against the value of the CustomAttributes. If you find a match of the combination of incoming request URL and the the respective Http Verb then you take that HttpControllerDiscriptor and return it from the SelectController() method..
This will allow you to have same URL with different methods in two different controllers.

Pass data from routes.php to a controller in Laravel

I am attempting to create a route in Laravel for a dynamic URL to load a particular controller action. I am able to get it to route to a controller using the following code:
Route::get('/something.html', array('uses' => 'MyController#getView'));
What I am having trouble figuring out is how I can pass a variable from this route to the controller. In this case I would like to pass along an id value to the controller action.
Is this possible in Laravel? Is there another way to do this?
You are not giving us enough information, so you need to ask yourself two basic questions: where this information coming from? Can you have access to this information inside your controller without passing it via the routes.php file?
If you are about to produce this information somehow in your ´routes.php´ file:
$information = WhateverService::getInformation();
You cannot pass it here to your controller, because your controller is not really being fired in this file, this is just a list of available routes, wich may or may not be hit at some point. When a route is hit, Laravel will fire the route via another internal service.
But you probably will be able to use the very same line of code in your controller:
class MyController extends BaseController {
function getView()
{
$information = WhateverService::getInformation();
return View::make('myview')->with(compact('information'));
}
}
In MVC, Controllers are meant to receive HTTP requests and produce information via Models (or services or repositores) to pass to your Views, which can produce new web pages.
If this information is something you have in your page and you want to sneak it to your something.html route, use a POST method instead of GET:
Route::post('/something.html', array('uses' => 'MyController#getView'));
And inside your controller receive that information via:
class MyController extends BaseController {
function getView()
{
$information = Input::get('information');
return View::make('myview')->with(compact('information'));
}
}

RESTful service in CodeIgniter

I am new to CodeIgniter, I want to build restful webservices using CodeIgniter. How can I post data to mysql and fetch from it back using REST services? I have gone through a web site 'tutplus', but it is explained there without mysql database.
Very simply, create some controllers, for example: user.php
At this controller write all necessary methods, exp: getUserInfo(), getUser(), getAge() and call these methods via URL.
To deal with this suggest:
https://ellislab.com/codeigniter/user-guide/general/controllers.html
https://ellislab.com/codeigniter/user-guide/general/routing.html
Actually on the project that i'm working on, we use RESTControllers, there's a project out there on github which extends codeigniter controller with all the REST capabilities:
https://github.com/chriskacerguis/codeigniter-restserver
All you need to do in your code it's include the file on the controller and extend that new controller:
require(APPPATH.'/libraries/REST_Controller.php');
class system extends REST_Controller {
}
You could also include the REST controller on the autoload libraries confinguration.
This library opens the 4 basic REST API as the GET, POST, PUT and DELETE
In your code the controller url should be declarated as this, so you would get a POST method on the index
public function index_post()
{
// ...just some code example
$this->response($book, 201); // Send an HTTP 201 Created
}
If you need a get on the index, you declare it as a GET method:
public function index_get()
{
// ...just some code example
$this->response($book, 201); // Send an HTTP 201 Created
}

symfony2 controller needs two ways of return-values, one for symfony-application (inside symfony) one for mobile (json)

I'm trying to build a restful JSON api for my Symfony2 Application.
I'm using the http://jmsyst.com/libs/serializer JMS\Serializer Bundle to serialize my Entities to JSON.
I have this example Controller-Action:
public function getFarmerByNameAction(Request $request) {
$this->setLocale($request);
$name = $request->get("name");
$farmer = $this->getDoctrine()->getRepository("FarmerguideBackendBundle:Farmer")->findByName($name);
// Return json response
return new Response($this->jsonify($farmer));
}
Since I'm using this serializer very often (I know I should do something like a singleton or whatever, but currently I don't have the time for that, I was just playing with the framework) I've put the code inside a function which does the serializing.
private function jsonify($object) {
// Serialize to json
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($object, 'json');
return $json;
}
My problem is the following:
This code is inside a BackendController, which does NOT contain any gui-specific information. So just a RESTful API.
In another Controller, let's say WebappController I have the code to access these backendfunctions and do some stuff with twig-files and render()-methods.
I want to access all these information via mobile over ajax (therefore I need this json return value)
What's the best-practice here? Is it better to say: Well if it's a ajax-call (check with if($request->isXmlHttpRequest())) , do jsonify right before returning the repsonse and if it's not return the entities (I need entities for twig-templates..) Or is there another approach?
Or is it even better to work with $request->getFormatType() and making the ajax call with contentType="application/json; charset=utf-8"
Here is how KnpBundles handles it https://github.com/KnpLabs/KnpBundles/blob/master/src/Knp/Bundle/KnpBundlesBundle/Controller/DeveloperController.php#L35
I guess you need to clearify what your intentions are. Because right now it seems as if your WebappController would just be a client to your Backendcontroller. Something like:
$result = file_get_contents('/path/to/backend/method/1/3');
You then simply go ahead and decode the json.
That is some additional overhead of course. If you want to get entities, I would suggest to create a Service for all your backend methods and return the entities there. You then simply call those methods from your BackendController and your WebappController. You then would only jsonify the entities in your BackendController and render the appropriate templates in your WebappController.

Resources