Skip to content
This repository has been archived by the owner on Apr 3, 2023. It is now read-only.

WebService

Jean-Guilhem Rouel edited this page Feb 24, 2016 · 1 revision

Table of Contents

The calculator Web Service

An observer of unicorn is simply a web service outputting results in a Unicorn-compatible format. In this first part of the tutorial, we're going to create a calculator web service following the specifications described in the [wiki:ObserverTutorial].

The service will be implemented in PHP as this language is fairly easy to read.

The calculator service has three parameters:

 * `uri`: the URI of the file to process
 * `x2`: multiplies results by two if present (its value doesn't matter)
 * `output`: the format to use to output results. Only `html` is available for this first section

The whole source code is available at the bottom of this page.

caculator.php

This is the main file. It contains the core functionnality of the calculator.

The following code is the entry point of the service. It checks that the `uri` parameter is present and that the corresponding resource exists before calling the function `process_file`.

The `process_file` function iterates over each line and calls `process_expression` which will be in charge of evaluating the expression.

process_expression first performs a quick sanity check to ensure the expression contains only valid symbols (digits, operators and parentheses). It then calls `eval` to evaluate the expression. Note that using `eval` is pretty bad as it can be very harmful. The earlier sanity check should prevent any misuse though and `eval` is very handy in this case (otherwise we would have had to write the evaluator ourselves).

If `eval` throws an error, it actually immediately sends it to the default output buffer. That's why we use the `ob_*` functions. They allow to keep any output in a buffer instead of directly sending it to the browser

The last part of the script is about rendering result in different formats. For now, we will only define a basic HTML output.

calculator_html.tpl

Template is a simple HTML document with embedded PHP in them. In this template, we iterate over errors and results and display them in definition lists.

What's Next

During this step, we wrote a very simple web calculator. Once deployed on a PHP-ready web server, you can call it through URLs like http://example.org/calculator.php?uri=http://example.org/calc.txt&x2=1.

In the [wiki:ObserverTutorial/Output], we will see how we can adapt this web service in order to make its integration in Unicorn possible.

Use an extra layer of security with two factor authentication (2FA) when logging into google

Clone this wiki locally