Skip to content

Instantly share code, notes, and snippets.

@esfand
Forked from evillemez/gist:6464513
Created May 24, 2014 04:00
Show Gist options
  • Save esfand/11c4d0872a0daea97bed to your computer and use it in GitHub Desktop.
Save esfand/11c4d0872a0daea97bed to your computer and use it in GitHub Desktop.

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(200, json_encode($result));
});

//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(201, json_encode($result));
});

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

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

//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(200, json_encode($result));
});

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

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

//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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment