ZiBaT => Peter Levinsky => Programming => exercise

PHP Twig
Simple MVC PHP

Updated : 2016-09-26

Exercise: PHP & Twig, simple calculator

revised after Anders Børjesson

Mission:

To create a PHP application in PHPStorm using a MVC framework (here Twig).

In this exercise you will make a simple calculator using PHP.

Precondition:

  1. SetUp and create a project in PhpStorm
  2. How to use Composer and Twig in your PHP project
  3. http://twig.sensiolabs.org/
  4. PHP Tutorial

exercise 1: Make a form to send calculation

Make a PHP web page (e.g. 'index.php') with a PHP/HTML form element.
This page / form should include two textfield for the two numbers to add plus a button to send the request.

The methods must be post, not get.

Exercise 2: Make a site to handle calculation

You are to make two pages (split in 'view' and 'control'), to follow the framework twig.

  1. A PHP page (control) to receive the request and make the calculation, which forward (render) the result to a viewpage.
  2. A TWIG page (view) to present the result

Exercise 2.1: Make a Page to do the calculation

Now make another PHP web page (e.g. 'calculate.php'):
This page is where you do the calculation. Send this result to the view page.

Exercise 2.2: make a page to present the result

Make a page to present the result (e.g. 'Calculation.html.twig').

Exercise 3: POST vS. GET

Normally you use <form method="post" ...>.

Try to use method="get".

What difference does it make?
Use $_REQUEST or $_GET. What is the difference?

General question: How are data transported with HTTP GET and HTTP POST?

Exercise 4: Next version, more arithmetic operators

The first version of the calculator only does Add ('+').

Next step is to add all 4 operations add, subtract, multiply, divide.

Add a drop down list to the form (HTML select) with +, -, *, and /, and maybe even more operators.

Adapt the server side to handle different kinds of calculations:

  1. First version: Use PHP if ... else ... elseif statements.
  2. Second version: Use a PHP switch statement.

Extra A: Refactoring: function

Make a user defined function to do the calculation.

  1. Simply wrap the PHP code in a function named calculate
    Make the function return the result.
    Use the result in echo.
  2. Make a copy of the function, name it calculate2
    Add parameters to the function: firstNumer, secondNumber, operationToBePerformed

Extra: Refactoring: class calculator

Make a PHP class calculator.

Inspiration (the first part only. The later part i quite advanced ...)

Extra: Refactoring: Separate file

Put the class calculator in a separate file.
Include the calculator file in the main file using the PHP syntax include or require.

Extra: CSS styling

Style your calculator to make it look nicer ...

Extra extra: Bootstrap

Style your calculator using the Bootstrap framework.