PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/labs/15 Modular PHP/worksheet.md

https://gitlab.com/jafar70/205CDE
Markdown | 330 lines | 269 code | 61 blank | 0 comment | 0 complexity | 23ed4eda06c17f426e15ed8799cb7c1d MD5 | raw file
  1. # Modular PHP
  2. in this lab you will use modular features of the PHP language, for example functions and classes.
  3. ## Task List
  4. in this lab you will do the following tasks:
  5. - write PHP functions
  6. - use predined functions
  7. - write PHP classes
  8. - create a JSON object as a response to an API call
  9. ### 1 Functions
  10. #### 1.1 Defining a Function
  11. A function in PHP has a same meaning as in other languages: it is a group of logically connected statements which have a name and which can
  12. be called using that name. A function can have parameters which should be named but types are not declared. A function can return a value but
  13. the type of the returned value should not be written in declaration.
  14. Syntax template is the following:
  15. ```
  16. function name($parameterName, ..., $parameterName) {
  17. statements;
  18. }
  19. ````
  20. Example:
  21. ```
  22. <!DOCTYPE html>
  23. <html>
  24. <head><title>Function example</title></head>
  25. <body>
  26. <?php
  27. function is_odd($number) {
  28. if (($number%2)==0)
  29. return FALSE;
  30. else
  31. return TRUE;
  32. }
  33. $checked_number=rand(0, 50); # random number generator
  34. if (is_odd($checked_number)==TRUE)
  35. print "<p>Number $checked_number is odd.</p>";
  36. else
  37. print "<p>Number $checked_number is even.</p>";
  38. ?>
  39. </body>
  40. </html>
  41. ```
  42. The latter if-statement looks a bit redundant. How would you get rid of it?
  43. #### 1.2 Parameter Types
  44. By default parameters are passed by value in PHP, meaning that the actual parameter ($checked_number above) value is copied into a formal parameter ($number) in each function call.
  45. This means that updating parameter value inside a function block does not affect to the value of the actual parameter in calling part of a program.
  46. A parameter can also be passed by reference which means that both parameters (actual and formal) are references to the same memory address and formal parameter can be thought as being an alias to the actual parameter. In this case a developer can pass information inside a function as well outside of it with parameters.
  47. A reference parameter should have a & mark before the usual $ mark.
  48. See the example below.
  49. ```
  50. <!DOCTYPE html>
  51. <html>
  52. <head><title>Function example</title></head>
  53. <body>
  54. <?php
  55. function is_odd(&$number) { # $number is now a reference parameter
  56. if (($number%2)==0) {
  57. $number++;
  58. return FALSE;
  59. }
  60. else {
  61. $number++;
  62. return TRUE;
  63. }
  64. }
  65. $checked_number=rand(0, 50);
  66. $checked_original_value = $checked_number;
  67. if (is_odd($checked_number)==TRUE)
  68. print "<p>Number $checked_original_value is odd. (incremented value $checked_number)</p>";
  69. else
  70. print "<p>Number $checked_original_value is even. (incremented value $checked_number)</p>";
  71. ?>
  72. </body>
  73. </html>
  74. ```
  75. #### 1.2 Scope
  76. A variable defined outside of a function have a global scope and can be seen throughout the program. A variable which is defined inside a function are local
  77. variables and have a local scope. They can be used only inside a function block they are defined.
  78. If a function wants to access to a global variable, global keyword is needed in front of the variable name. See the example below.
  79. ```
  80. <!DOCTYPE html>
  81. <html>
  82. <head><title>Function example</title></head>
  83. <body>
  84. <?php
  85. function is_odd() {
  86. global $checked_number; # global variable
  87. $number=0; # local variable (just for demo purpose)
  88. if (($checked_number%2)==0) {
  89. $number++;
  90. return FALSE;
  91. }
  92. else {
  93. $number++;
  94. return TRUE;
  95. }
  96. }
  97. $checked_number=rand(0, 50);
  98. if (is_odd($checked_number)==TRUE)
  99. print "<p>Number $checked_number is odd. </p>";
  100. else
  101. print "<p>Number $checked_number is even. </p>";
  102. ?>
  103. </body>
  104. </html>
  105. ```
  106. ### 2 Files
  107. PHP allows access to resources on the server. One such a resource is the files on the server. PHP has powerful and fairly easy to use file related functions.
  108. Below is a table containing some useful I/O related functions.
  109. | function names | category |
  110. | ------------------------------------------------- |:--------------------------------:|
  111. | file,file_get_contents,file_put_contents | reading/writing entire files |
  112. | basename,file_exists,filesize,fileperms,filemtime | asking for information |
  113. | is_dir,is_readable,is_writable,disk_free_space | asking for information |
  114. |copy,rename,unlink,chmod,chgrp,chown,mkdir,rmdir |manipulating files and directories|
  115. |glob,scandir |reading directories |
  116. An example below reverses lines of a text file (The example is found from the book Stepp, Miller, Kirst:"Web Programming Step bt Step").
  117. ```php
  118. <?php
  119. function reverse_lines($filename) {
  120. $text = file_get_contents($filename);
  121. $lines = explode("\n", $text); # split in lines
  122. $lines = array_reverse($lines);
  123. $text = implode("\n", $lines); # connect lines to a single string
  124. file_put_contents($filename, $text);
  125. }
  126. print file_get_contents("myfile.txt");
  127. reverse_lines("myfile.txt");
  128. print file_get_contents("myfile.txt");
  129. ?>
  130. ```
  131. ### 3 REST API - a Simple Example
  132. Here is a simple REST API [example][RESTAPI] found from the web. In the example the first PHP program creates an api implementation and the second is a client which creates api calls.
  133. The API implementation is below:
  134. ```php
  135. <?php
  136. // This is the API, 2 possibilities: show the app list or show a specific app by id.
  137. // This would normally be pulled from a database but for demo purposes, I will be hardcoding the return values.
  138. function get_app_by_id($id)
  139. {
  140. $app_info = array();
  141. // normally this info would be pulled from a database.
  142. // build JSON array.
  143. switch ($id){
  144. case 1:
  145. $app_info = array("app_name" => "Web Demo", "app_price" => "Free", "app_version" => "2.0");
  146. break;
  147. case 2:
  148. $app_info = array("app_name" => "Audio Countdown", "app_price" => "Free", "app_version" => "1.1");
  149. break;
  150. case 3:
  151. $app_info = array("app_name" => "The Tab Key", "app_price" => "Free", "app_version" => "1.2");
  152. break;
  153. case 4:
  154. $app_info = array("app_name" => "Music Sleep Timer", "app_price" => "Free", "app_version" => "1.9");
  155. break;
  156. }
  157. return $app_info;
  158. }
  159. function get_app_list()
  160. {
  161. //normally this info would be pulled from a database.
  162. //build JSON array
  163. $app_list = array(array("id" => 1, "name" => "Web Demo"), array("id" => 2, "name" => "Audio Countdown"), array("id" => 3, "name" => "The Tab Key"), array("id" => 4, "name" => "Music Sleep Timer"));
  164. return $app_list;
  165. }
  166. $possible_url = array("get_app_list", "get_app");
  167. $value = "An error has occurred";
  168. if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
  169. {
  170. switch ($_GET["action"])
  171. {
  172. case "get_app_list":
  173. $value = get_app_list();
  174. break;
  175. case "get_app":
  176. if (isset($_GET["id"]))
  177. $value = get_app_by_id($_GET["id"]);
  178. else
  179. $value = "Missing argument";
  180. break;
  181. }
  182. }
  183. //return JSON array
  184. exit(json_encode($value));
  185. ?>
  186. ```
  187. The edited client implementation is below:
  188. ```
  189. <html>
  190. <body>
  191. <?php
  192. $server = $_SERVER['HTTP_HOST'];
  193. if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_app")
  194. {
  195. $app_info = file_get_contents('http://'.$server.'/api.php?action=get_app&id=' . $_GET["id"]);
  196. $app_info = json_decode($app_info, true);
  197. ?>
  198. <table>
  199. <tr>
  200. <td>App Name: </td><td> <?php echo $app_info["app_name"] ?></td>
  201. </tr>
  202. <tr>
  203. <td>Price: </td><td> <?php echo $app_info["app_price"] ?></td>
  204. </tr>
  205. <tr>
  206. <td>Version: </td><td> <?php echo $app_info["app_version"] ?></td>
  207. </tr>
  208. </table>
  209. <br />
  210. <a href="http://<?php echo $server?>/REST_Client.php?action=get_app_list" alt="app list">Return to the app list</a>
  211. <?php
  212. }
  213. else // else take the app list
  214. {
  215. $app_list = file_get_contents('http://'.$server.'/api.php?action=get_app_list');
  216. $app_list = json_decode($app_list, true);
  217. //var_dump($app_list);
  218. ?>
  219. <ul>
  220. <?php foreach ($app_list as $app) { ?>
  221. <li>
  222. <a href=<?php echo "http://$server/REST_Client.php?action=get_app&id=" . $app["id"] ?> alt=<?php echo "app_" . $app["id"] ?>><?php echo $app["name"] ?></a>
  223. </li>
  224. <?php } ?>
  225. </ul>
  226. <?php
  227. } ?>
  228. </body>
  229. </html>
  230. ```
  231. These are the API calls in this example:
  232. - http://drink-office.codio.io:3000/REST_Client.php?action=get_app&id=1 (drink-office.codio.io:3000 is the host name which may vary.)
  233. - http://drink-office.codio.io:3000/REST_Client.php?action=get_app&id=2
  234. - http://drink-office.codio.io:3000/REST_Client.php?action=get_app&id=3
  235. - http://drink-office.codio.io:3000/REST_Client.php?action=get_app&id=4
  236. - http://drink-office.codio.io:3000/REST_Client.php?action=get_app_list
  237. The API implementation returns a specific JSON object related to the query string id value. The query string variable "get_app_list" is used to create a menu if there is a need to run client more than once.
  238. Notice how a PHP program obtain access to the HTTP query ids and to the query id values.
  239. ### 4 Object Oriented PHP
  240. PHP can be used as an object oriented language i.e. a developer can create classes and objects and use other object oriented features.
  241. The syntax template for PHP class is the following:
  242. ```php
  243. class name {
  244. private $name; # member attribute (class data in each object)
  245. public function __contruct(name) { # constructor
  246. statements;
  247. }
  248. public function name(parameters) { # member method
  249. statements;
  250. }
  251. }
  252. ```
  253. When accessing class members inside class member functions an implicit reference $this should be used.
  254. Further reading: [PHP home page][PHP]
  255. [PHP]: http://php.net/manual/en/
  256. [RESTAPI]: http://blog.ijasoneverett.com/2013/02/rest-api-a-simple-php-tutorial/
  257. ### Test Your Understanding
  258. It is good to be able reed some data when doing these exercises. There are two small php-scrits (Showform.php, getInput.php) included, which can be useful. Feel free to use them if you like.
  259. 1. Write a PHP function which gets user name and age as input and prints them out.
  260. 2. Write a PHP function which reverses characters of the input string and prints the result out. So input string "John" is printed out as "nhoJ".
  261. 3. Write a PHP function that prints out prime numbers from 2 to some maximum, the maximum is given as input.
  262. 4. Write a PHP function which randomly chooses (and prints) one line from the list of words found from here: http://www.webstepbook.com/words.txt.
  263. 5. Write a PHP program that calculates an area of a circle when the radius is known. Make this version based on the REST API (radius is read from an HTTP query string and the result is returned as a JSON object).
  264. 6. Write a traffic card program using PHP class which makes it possible to “travel” in public transportation (in busses, trams, etc.). Define a TrafficCard class which has at least the following features:
  265. a. a card initialization (who’s the owner, assign zero to a balance)
  266. b. loading a value to the card (euros/pounds)
  267. c. traveling using a card
  268. d. two different charges: 2.80 euros/pounds in city central and 4 euros/pounds in areas outside of a city.
  269. Consider what operations a card must include. Implement the TrafficCard class and test that it functions as should (for example a balance can never be negative).