Commits

Anonymous committed 4ba232b

adding tutorial code to public repo

  • Participants

Comments (0)

Files changed (16)

+<VirtualHost *:80>
+    ServerName api.local
+    ServerAdmin admin@localhost
+    DocumentRoot /var/www/myapi/public
+
+    <Directory /var/www/myapi/public>
+        AllowOverride All
+        Order deny,allow
+        Allow from All
+    </Directory>
+</VirtualHost>

public/find-header.php

+<?php
+/*
+ * Use this script to see what accept header was sent
+ * */
+
+echo ($_SERVER['HTTP_ACCEPT']);

public/headers-accept.php

+<?php
+
+function parseAcceptHeader( $header )
+{
+    if ( !preg_match_all(
+            '(
+                (?P<value>[a-z*][a-z0-9_/*+.-]*)
+                    (?:;q=(?P<priority>[0-9.]+))?
+             \\s*(?:,|$))ix', $header, $matches, PREG_SET_ORDER ) )
+    {
+        return false;
+    }
+
+    $accept = array();
+    foreach ( $matches as $values )
+    {
+        if(!isset($values['priority']) || 
+            (isset($values['priority']) && $values['priority'] == 1))
+        {
+            $accept[] = isset( $values['value'] ) ? strtolower( $values['value'] ) : null;
+        }
+    }
+
+    return $accept;
+}
+
+$data = array(
+    'format' => 'json',
+    'status' => 'live'
+    );
+
+$original_accept_header = $_SERVER['HTTP_ACCEPT'];
+
+$accept = parseAcceptHeader($original_accept_header);
+
+if(in_array('text/html', $accept)) {
+    header('Content-Type: text/html');
+    echo "<pre>";
+    print_r($data);
+    echo "</pre>";
+} elseif(in_array('text/xml', $accept)) {
+    $simplexml = simplexml_load_string('<?xml version="1.0" ?><data />');
+    foreach($data as $key => $value) {
+        $simplexml->addChild($key, $value);
+    }
+
+    header('Content-Type: text/xml');
+    echo $simplexml->asXML();
+} else {
+    // return json
+    header('Content-Type: application/json');
+    echo json_encode($data);
+}
+

public/headers.php

+<?php
+
+$data = array(
+    'status' => 'live',
+    'now' => time()
+    );
+
+if(false !== strpos($_SERVER['HTTP_ACCEPT'], 'text/html')) {
+    header('Content-Type: text/html');
+    echo "<pre>";
+    print_r($data);
+    echo "</pre>";
+} elseif(false !== strpos($_SERVER['HTTP_ACCEPT'], 'text/xml')) {
+    $simplexml = simplexml_load_string('<?xml version="1.0" ?><data />');
+    foreach($data as $key => $value) {
+        $simplexml->addChild($key, $value);
+    }
+
+    header('Content-Type: text/xml');
+    echo $simplexml->asXML();
+} else {
+    // return json
+    header('Content-Type: application/json');
+    echo json_encode($data);
+}
+<?php
+
+$data = array(
+    'format' => 'json',
+    'status' => 'live'
+);
+
+echo json_encode($data);

public/rest/.htaccess

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

public/rest/controllers.php

+<?php
+
+class UsersController {
+    public function GETAction($parameters) {
+        $users = array();
+        // imagine retreving data from models
+
+        $users[0] = array('name' => 'Harry Potter',
+            'age' => 14,
+            'house' => 'Gryffindor'
+        );
+        $users[1] = array('name' => 'Hermione Granger',
+            'age' => 14,
+            'house' => 'Gryffindor'
+        );
+        $users[2] = array('name' => 'Ron Weasley',
+            'age' => 14,
+            'house' => 'Gryffindor'
+        );
+        $users[3] = array('name' => 'Ginny Weasley',
+            'age' => 13,
+            'house' => 'Gryffindor'
+        );
+        $users[4] = array('name' => 'Cho Chang',
+            'age' => 15,
+            'house' => 'Ravenclaw'
+        );
+
+        $friends[0] = array( // Harry's friends
+            'http://api.local/rest/user/1',
+            'http://api.local/rest/user/2',
+            'http://api.local/rest/user/3',
+            'http://api.local/rest/user/4'
+        );
+
+        $friends[1] = array( // Hermione's friends 
+            'http://api.local/rest/user/0',
+            'http://api.local/rest/user/2',
+            'http://api.local/rest/user/3'
+        );
+
+            
+
+        if(isset($parameters[2])) {
+            if(isset($parameters[3]) && $parameters[3] == 'friends') {
+                return $friends[(int)$parameters[2]];
+            } else {
+                return $users[(int)$parameters[2]];
+            }
+        } else {
+            return $users;
+        }
+    }
+
+    public function POSTAction() {
+        // sanitise and validate data please!
+        $data = $_POST;
+
+        // create a user from params
+        $user['name'] = $data['name'];
+
+        // save the user, return the new id
+
+        // redirect user
+        header('HTTP/1.1 201 Created');
+        header('Location: http://api.local/rest/users/5');        
+        return $user;
+    }
+}

public/rest/index.php

+<?php
+
+// inclue the various view classes
+include('views.php');
+include('controllers.php');
+
+// work out what format they want
+$accept = explode(',', $_SERVER['HTTP_ACCEPT']);
+if($accept[0] == 'text/html') {
+    $view = new HtmlView();
+} elseif($accept[0] == 'text/xml') {
+    $view = new XmlView();
+} else {
+    $view = new JsonView();
+}
+
+// route the request
+$verb = $_SERVER['REQUEST_METHOD'];
+$action_name = strtoupper($verb) . 'Action';
+$url_params = explode('/',$_SERVER['PATH_INFO']);
+$controller_name = ucfirst($url_params[1]) . 'Controller';
+$controller = new $controller_name();
+$data = $controller->$action_name($url_params);
+
+// output appropriately
+$view->render($data);

public/rest/views.php

+<?php
+
+class ApiView {
+}
+
+class JsonView extends ApiView {
+    public function render($content) {
+        header('Content-Type: application/json');
+        echo json_encode($content);
+        return true;
+    }
+}
+
+class HtmlView extends ApiView {
+    public function render($content) {
+        header('Content-Type: text/html');
+        echo "<pre>";
+        print_r($content);
+        echo "</pre>";
+        return true;
+    }
+}
+
+class XmlView extends ApiView {
+    public function render($content) {
+        $simplexml = simplexml_load_string('<?xml version="1.0" ?><data />');
+        foreach($content as $key => $value) {
+            $simplexml->addChild($key, $value);
+        }
+
+        header('Content-Type: text/xml');
+        echo $simplexml->asXML();
+        return true;
+    }
+}
+
+
+

public/rpc/actions.php

+<?php
+
+class Actions {
+    public function getSiteStatus() {
+        return array('status' => 'healthy',
+            'time' => date('d-M-Y H:i'));
+    }
+
+    public function addTwoNumbers($params) {
+        return array('result' => ($params['a'] + $params['b']));
+    }
+}

public/rpc/index.php

+<?php
+
+// inclue the various view classes
+include('views.php');
+include('actions.php');
+
+// work out what format they want
+$accept = explode(',', $_SERVER['HTTP_ACCEPT']);
+if($accept[0] == 'text/html') {
+    $view = new HtmlView();
+} elseif($accept[0] == 'text/xml') {
+    $view = new XmlView();
+} else {
+    $view = new JsonView();
+}
+
+// route the request (filter input!)
+$action = $_GET['action'];
+$library = new Actions();
+// OBVIOUSLY you would filter input at this point
+$data = $library->$action($_GET);
+
+// output appropriately
+$view->render($data);

public/rpc/views.php

+<?php
+
+class ApiView {
+}
+
+class JsonView extends ApiView {
+    public function render($content) {
+        header('Content-Type: application/json');
+        echo json_encode($content);
+        return true;
+    }
+}
+
+class HtmlView extends ApiView {
+    public function render($content) {
+        header('Content-Type: text/html');
+        echo "<pre>";
+        print_r($content);
+        echo "</pre>";
+        return true;
+    }
+}
+
+class XmlView extends ApiView {
+    public function render($content) {
+        $simplexml = simplexml_load_string('<?xml version="1.0" ?><data />');
+        foreach($content as $key => $value) {
+            $simplexml->addChild($key, $value);
+        }
+
+        header('Content-Type: text/xml');
+        echo $simplexml->asXML();
+        return true;
+    }
+}
+
+
+

public/soap/Library.php

+<?php
+
+class Library {
+    public function thinkOfANumber() {
+        return 42;
+    }
+
+    public function thinkOfAName() {
+        return 'Arthur Dent';
+    }
+}

public/soap/index.php

+<?php
+
+include('Library.php');
+
+$options = array('uri' => 'http://api.local/soap');
+$server = new SoapServer(NULL, $options);
+$server->setClass('Library');
+
+$server->handle();

public/soap/no-soap-demo.php

+<?php
+
+include('Library.php');
+
+$lib = new Library();
+$name = $lib->thinkOfAName();
+echo $name; //Arthur Dent

public/soap/soap-demo.php

+<?php
+
+$options = array('uri' => 'http://api.local',
+    'location' => 'http://api.local/soap/');
+$client = new SoapClient(NULL, $options);
+
+$name = $client->thinkOfAName();
+echo $name;
+
+