jakubjosef
1/20/2014 - 4:28 PM

gistfile1.md

A cleaner way

The original blog post can be found here: http://blog.brunoscopelliti.com/building-a-restful-service-with-angularjs-and-php-backend-setup. I've tried to keep the logic the same as the original post.

Step 1: Composer

Write a composer.json, and require Silex. If you don't know about composer, you can learn about it at getcomposer.org. It's a package manager for PHP like NPM for node, most major projects now use this for managing dependencies.

{
  "require": {
    "silex/silex": "~1.0"
  }
}

Run php composer.phar install to install it.

Step 2: Write app

Here's the example from the blog post, written with Silex - this would result and an easy-to-maintain and testable application - just like the Angular.js counterpart on the front-end.

<?php
//index.php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

require 'vendor/autoload.php';

$app = new Silex\Application();

//a service to get your custom library from any controller
$app['library'] = function($app) {
  return new Library();
};

//get all books
$app->get('/book', function() use ($app) {
  $result = $app['library']->get_books();

  return new Response(json_encode($result),200);
});

//create new book
$app->post('/book', function(Request $req) use ($app) {
  $result = $app['library']->register_new_book($req->request->all()); //equivalent of "$_POST"

  return new Response(json_encode($result),201);
});

//get specific book
$app->get('/book/{id}', function($id) use ($app) {
  $result = $app['library']->get_book_by_id($id);

  return new Response(json_encode($result),200);
});

//loan specific book
$app->put('/book/{id}', function($id, Request $req) use ($app) {
  $d = json_decode($req->getContents());
  $result = $app['library']->loan_book($d);

  return new Response(json_encode($result),200);
});

//delete specific book
$app->delete('/book/{id}', function($id) use ($app) {
  $result = $app['library']->delete_book($id);

  return new Response(json_encode($result),200);
});

//run the app to handle the incoming request
//404, 405 responses are handled automatically
$app->run();

Step 3: .htaccess

Write an .htaccess to rewrite and remove the index.php from the url. This gives you the http://example.com/books/2 urls you want to see for the angular demo.

<IfModule mod_rewrite.c>
    RewriteEngine On
    #RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>