ZiBaT
=> Peter Levinsky
=> Programming => exercise |
PHP Twig |
Updated : 2016-09-26
|
To create a PHP application in PHPS
The REST API is running on : http://rest-pele-easj.azurewebsites.net/service1.svc/books/
Try it using 1) a browser (http://rest-pele-easj.azurewebsites.net/service1.svc/books/) 2) fiddler or 3) Postman
Make a PHP application e.g. 'ConsumeBooks', init composer, add twig and set up xampp.
Make a simple index.html file as start up page with some simple forms.
see interface-file IBookstoreService
In the index make a simple link (e.g. <a href="control/allBooks.php>Get all books</a>
Create in the controller folder a php-file e.g. 'allBooks.php'
This php-file must get all the books follow these two steps
1) create a get-request using 'file_get_content(<<uri>>)' where uri is the location of the REST api (i.e. http://rest-pele-easj.azurewebsites.net/service1.svc/books
/ )
2) the result is a json context i.e. you have to decode usin json_decode (<<result of the file-get>>)
Send these information to the twig - remember to give a name e.g. $res = array('books' => $resultOfJsonDecode)
Create the twig file in the folder 'view'. Show the information in the twig file properbly using the for loop (e.g. {% for book in books %})
In your index.html make a form to send a book id.
e.g.
<form action="control/getBook.php" method="post">
.....
Book id
<input type="number" name="id" />
<input type="submit" value="Search" />
</form>
create the php-file (e.g. getBook.php)
read the input from the form e.g. $id = $_POST['id'];
make a new get request like in exercise 3 but with ''uri + <</id>>''
You can make a new page for display or resue the previous one with a list books with only one element.
In your index-file make a form to create new books needed the values (Author, Title, Publisher, Price)
Create the php-file.
To send a book over the net you need to create a json-encoded string.
1) read input from form
2) create the data in an array e.g.
$data = array("Author" => $author, "Title" => $title, "Publisher" => $publisher, "Price" => $price);
3) encode the data using json_encode
4) build requst in curl e.g.
$ch = curl_init($URI);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // set request method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);// set data in body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', // set mime type I send json
'Content-Length: ' . strlen($data_string)) // length of data
);
$jsondata = curl_exec($ch); // send the request
5) send content to twig-page for displaying
You can create another web-site in the azure e.g. i have web-pele-easj for 'normal' web (soap/rest in c#) and php-pele-easj for PHP.
Deploy your PHP calculator to Azure. Follow the help instruction