├── Chapter07 ├── sample │ ├── to-copy.txt │ ├── to-move.txt │ ├── to-delete.txt │ ├── write-with-fpc.txt │ ├── write-with-fwrite.txt │ ├── users_list.csv │ └── users_list_enclosed.csv ├── Activity7.1 │ ├── tests │ │ ├── views │ │ │ └── testView.php │ │ ├── autoload.php │ │ ├── db │ │ │ └── setUp.sql │ │ └── Tests │ │ │ ├── TemplateTest.php │ │ │ ├── UserTest.php │ │ │ ├── RouterTest.php │ │ │ ├── HandlerTest.php │ │ │ └── AuthTest.php │ ├── src │ │ ├── templates │ │ │ ├── home.php │ │ │ ├── profile.php │ │ │ ├── main.php │ │ │ ├── login-form.php │ │ │ └── signup-form.php │ │ ├── handlers │ │ │ ├── Logout.php │ │ │ ├── Profile.php │ │ │ ├── Handler.php │ │ │ ├── Login.php │ │ │ └── Signup.php │ │ ├── components │ │ │ ├── Template.php │ │ │ ├── Auth.php │ │ │ └── Router.php │ │ └── models │ │ │ └── User.php │ ├── app_contacts.sql │ ├── app_users.sql │ ├── structure.sql │ └── web │ │ └── index.php ├── Exercise7.1 │ └── file_get_contents.php ├── Exercise7.3 │ ├── file_get_contents-memory.php │ └── fread-memory.php ├── db-common │ ├── connection-no-db.php │ ├── connection.php │ └── singleton.php ├── Exercise7.13 │ ├── db-common │ │ └── connection-no-db.php │ └── create-schema.php ├── Exercise7.14 │ ├── db-common │ │ └── connection.php │ └── create-table.php ├── Exercise7.15 │ ├── db-common │ │ └── connection.php │ └── insert.php ├── Exercise7.16 │ ├── db-common │ │ └── connection.php │ └── insert-prepared.php ├── Exercise7.17 │ ├── db-common │ │ └── connection.php │ └── select-all.php ├── Exercise7.18 │ ├── db-common │ │ └── connection.php │ └── update.php ├── Exercise7.19 │ ├── db-common │ │ └── connection.php │ └── delete.php ├── Exercise7.6 │ └── download.php ├── Exercise7.9 │ └── delete.php ├── Exercise7.4 │ └── fgets.php ├── Exercise7.12 │ └── connect.php ├── Exercise7.5 │ └── fgetcsv.php ├── Exercise7.2 │ └── fread.php ├── Exercise7.11 │ └── copy.php ├── Example │ └── DatabaseSingleton.php ├── Exercise7.7 │ └── write.php ├── Exercise7.8 │ └── write-append.php └── Exercise7.10 │ └── move.php ├── Chapter01 ├── Exercise1.1 │ └── Exercise1.1.php ├── Exercise1.2 │ └── hello.php ├── Exercise1.3 │ └── hello.php ├── Exercise1.6 │ └── hello.php ├── Exercise1.4 │ └── hello.php ├── Exercise1.7 │ └── server.php ├── Exercise1.9 │ └── isset.php ├── Exercise1.8 │ └── assignment.php ├── Examples │ └── Example1.01.php ├── Activity1.1 │ └── movies.php └── Exercise1.5 │ └── login-form.html ├── Chapter06 ├── Activity6.1 │ ├── tests │ │ ├── views │ │ │ └── testView.php │ │ ├── autoload.php │ │ └── Tests │ │ │ ├── TemplateTest.php │ │ │ ├── RouterTest.php │ │ │ └── HandlerTest.php │ ├── src │ │ ├── handlers │ │ │ ├── Logout.php │ │ │ ├── Handler.php │ │ │ └── Login.php │ │ ├── components │ │ │ ├── Template.php │ │ │ └── Router.php │ │ └── templates │ │ │ ├── main.php │ │ │ └── login-form.php │ └── web │ │ └── index.php ├── Exercise6.11 │ └── bootstrap │ │ ├── tests │ │ ├── views │ │ │ └── testView.php │ │ ├── autoload.php │ │ └── Tests │ │ │ ├── TemplateTest.php │ │ │ ├── RouterTest.php │ │ │ └── HandlerTest.php │ │ ├── src │ │ ├── templates │ │ │ ├── profile.php │ │ │ ├── main.php │ │ │ └── login-form.php │ │ ├── handlers │ │ │ ├── Logout.php │ │ │ ├── Handler.php │ │ │ ├── Profile.php │ │ │ └── Login.php │ │ └── components │ │ │ ├── Template.php │ │ │ └── Router.php │ │ └── web │ │ └── index.php ├── Exercise6.1 │ └── super-server.php ├── Exercise6.10 │ └── bootstrap-homepage │ │ ├── tests │ │ ├── views │ │ │ └── testView.php │ │ ├── autoload.php │ │ └── Tests │ │ │ └── TemplateTest.php │ │ ├── web │ │ └── index.php │ │ └── src │ │ ├── components │ │ └── Template.php │ │ └── templates │ │ └── main.php ├── Exercise6.6 │ ├── my-image.png │ └── super-post-upload.php ├── Exercise6.8 │ └── output-escape-reflected.php ├── Exercise6.2 │ └── super-cookie.php ├── Exercise6.9 │ └── form-csrf.php ├── Exercise6.3 │ └── session.php ├── Exercise6.4 │ └── super-get-href.php ├── Exercise6.5 │ └── super-post-form.php └── Exercise6.7 │ └── input-sanitize.php ├── Chapter08 ├── Activity8.1 │ └── tests │ │ ├── autoload.php │ │ ├── Tests │ │ ├── PrintTest.php │ │ └── FactorialTest.php │ │ └── function │ │ └── factorial.php ├── Exercise8.1 │ └── custom-handler.php ├── err-common │ ├── error-handler.php │ ├── exception-handler.php │ └── all-errors-handler.php ├── Exercise8.3 │ ├── err-common │ │ └── error-handler.php │ └── sqrt.php ├── Exercise8.4 │ ├── err-common │ │ └── error-handler.php │ └── on-shutdown.php ├── Exercise8.7 │ ├── err-common │ │ └── exception-handler.php │ └── basic-try-handler.php ├── Exercise8.2 │ └── log-handler.php ├── Exercise8.5 │ ├── basic-try.php │ └── basic-try-all.php ├── Exercise8.10 │ ├── err-common │ │ └── all-errors-handler.php │ └── date.php ├── Exercise8.8 │ ├── err-common │ │ └── all-errors-handler.php │ └── sqrt-all.php ├── Exercise8.9 │ ├── err-common │ │ └── all-errors-handler.php │ └── run.php └── Exercise8.6 │ └── validate-email.php ├── Chapter04 ├── Exercise4.1 │ └── hello.php ├── Exercise4.2 │ └── print_r.php ├── Examples │ ├── TestSayHello.php │ ├── array-use-sort-with-flags.php │ ├── function-with-default-value.php │ ├── how-many-times-did-we-tell-you.php │ └── function-average.php ├── Exercise4.7 │ ├── TestSayHello.php │ ├── variable-hello.php │ └── function-with-default-value.php ├── Exercise4.6 │ ├── callable.php │ └── how-many-times-did-we-tell-you.php ├── Exercise4.3 │ ├── array-use-sort-with-flags.php │ └── array-functions.php ├── Exercise4.4 │ └── count-me-with-GLOBALS.php ├── Exercise4.5 │ └── add.php ├── Exercise4.8 │ └── activity-functions.php └── Activity4.1 │ └── activity.php ├── Bonus chapters ├── Bonus Chapter_11.pdf └── Bonus Chapter_11_Activity_Solution.pdf ├── Chapter09 ├── Exercise9.8 │ ├── index.php │ └── Example.php ├── Exercise9.9 │ ├── index.php │ ├── Example.php │ └── composer.json ├── Activity9.1 │ ├── index.php │ └── Example.php └── Exercise9.2 │ └── composer.json ├── Chapter10 ├── sample.json ├── sample.xml ├── Exercise10.1 │ ├── json.php │ └── MailingListRecipient.php ├── Exercise10.3 │ └── guzzle-example │ │ ├── composer.json │ │ └── ipify.php ├── Activity10.1 │ └── httpbin.php └── Exercise10.4 │ └── spamcheck.php ├── Chapter03 ├── Exercise3.5 │ └── print-numbers-while.php ├── Exercise3.1 │ └── test-sunday.php ├── Exercise3.11 │ └── print-numbers-continue.php ├── Exercise3.6 │ └── print-numbers-do-while.php ├── Exercise3.8 │ └── print-days-foreach.php ├── Exercise3.7 │ └── print-days-for.php ├── Exercise3.3 │ └── test-age.php ├── Exercise3.10 │ └── print-numbers-break.php ├── Exercise3.2 │ └── test-difference.php ├── Exercise3.9 │ └── print-professions-subjects.php ├── Exercise3.4 │ └── test-datatype.php └── Activity3.1 │ └── activity-movies.php ├── Chapter05 ├── Exercise5.10 │ ├── DriveInterface.php │ ├── Van.php │ ├── Motorcycle.php │ └── Car.php ├── Exercise5.11 │ ├── DriveInterface.php │ ├── PriceTrait.php │ └── Motorcycle.php ├── Exercise5.7 │ ├── DriveInterface.php │ ├── AbstractVehicle.php │ ├── Motorcycle.php │ └── Car.php ├── Exercise5.8 │ ├── DriveInterface.php │ ├── AbstractVehicle.php │ ├── Car.php │ └── Motorcycle.php ├── Exercise5.9 │ ├── DriveInterface.php │ ├── Motorcycle.php │ └── Car.php ├── Exercise5.12 │ ├── Vehicle │ │ └── DriveInterface.php │ └── Traits │ │ └── PriceTrait.php ├── Activity5.1 │ ├── Student │ │ └── Student.php │ ├── activity-classes.php │ └── Professor │ │ └── Professor.php ├── Examples │ ├── interface.php │ ├── trait-testing.php │ ├── MyClass.php │ ├── Class-hints.php │ ├── MySimpleClass.php │ ├── User.php │ ├── method-overloading.php │ ├── namespace.php │ ├── MyMagicMethodClass.php │ ├── Person.php │ ├── attribute-overloading.php │ └── MyMagicClass.php ├── Exercise5.4 │ ├── vehicle-visibility.php │ ├── Car.php │ └── Vehicle.php ├── Exercise5.3 │ ├── Motorcycle.php │ ├── Car.php │ └── Vehicle.php ├── Exercise5.2 │ ├── vehicle-objects.php │ └── Vehicle.php ├── Exercise5.5 │ ├── Motorcycle.php │ ├── Car.php │ └── Vehicle.php ├── Exercise5.6 │ ├── Motorcycle.php │ ├── Car.php │ └── AbstractVehicle.php └── Exercise5.1 │ └── Vehicle.php ├── Chapter02 ├── Exercise2.4 │ └── convertintstring.php ├── Activity2.1 │ └── tracker.php ├── Exercise2.5 │ └── activity-height.php ├── Exercise2.1 │ └── order.php ├── Exercise2.3 │ └── convertbooleanint.php └── Exercise2.2 │ └── array.php └── LICENSE /Chapter07/sample/to-copy.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter07/sample/to-move.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter07/sample/to-delete.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter07/sample/write-with-fpc.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter07/sample/write-with-fwrite.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.1/Exercise1.1.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/tests/views/testView.php: -------------------------------------------------------------------------------- 1 |

Name is

2 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/views/testView.php: -------------------------------------------------------------------------------- 1 |

Name is

2 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.3/hello.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.6/hello.php: -------------------------------------------------------------------------------- 1 |

!

2 |
-------------------------------------------------------------------------------- /Chapter08/Activity8.1/tests/autoload.php: -------------------------------------------------------------------------------- 1 | Name is

2 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.4/hello.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.7/server.php: -------------------------------------------------------------------------------- 1 | '; 3 | print_r($_SERVER); 4 | echo '
';
5 | ?>


--------------------------------------------------------------------------------
/Chapter06/Exercise6.1/super-server.php:
--------------------------------------------------------------------------------
1 | %s
", print_r($_SERVER, true)); 2 | -------------------------------------------------------------------------------- /Chapter07/sample/users_list.csv: -------------------------------------------------------------------------------- 1 | John,Smith,2019-03-31T10:20:30Z 2 | Alice,Smith,2019-02-28T12:13:14Z 3 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.10/bootstrap-homepage/tests/views/testView.php: -------------------------------------------------------------------------------- 1 |

Name is

2 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.1/file_get_contents.php: -------------------------------------------------------------------------------- 1 | doSomething(); 9 | -------------------------------------------------------------------------------- /Chapter10/sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "property": "value", 3 | "some array": [ 4 | {"item 1": "some value"}, 5 | {"item 2": "some other value"} 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Bonus chapters/Bonus Chapter_11_Activity_Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktWorkshops/The-PHP-Workshop/HEAD/Bonus chapters/Bonus Chapter_11_Activity_Solution.pdf -------------------------------------------------------------------------------- /Chapter04/Exercise4.2/print_r.php: -------------------------------------------------------------------------------- 1 | 2 | value 3 | 4 | some value 5 | some other value 6 | 7 | -------------------------------------------------------------------------------- /Chapter03/Exercise3.8/print-days-foreach.php: -------------------------------------------------------------------------------- 1 | engineStatus = true; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter07/sample/users_list_enclosed.csv: -------------------------------------------------------------------------------- 1 | John,Smith,2019-03-31T10:20:30Z,"4452 Norma Lane 2 | Alexandria 3 | 71302 Louisiana" 4 | Alice,Smith,2019-02-28T12:13:14Z,"4452 Norma Lane 5 | Alexandria 6 | 71302 Louisiana" 7 | -------------------------------------------------------------------------------- /Chapter04/Exercise4.7/variable-hello.php: -------------------------------------------------------------------------------- 1 | name = $name; 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter05/Exercise5.11/PriceTrait.php: -------------------------------------------------------------------------------- 1 | price; 8 | } 9 | 10 | public function setPrice($price) 11 | { 12 | $this->price = $price; 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter03/Exercise3.7/print-days-for.php: -------------------------------------------------------------------------------- 1 | price; 8 | } 9 | 10 | public function setPrice($price) 11 | { 12 | $this->price = $price; 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter07/db-common/connection-no-db.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter04/Exercise4.7/function-with-default-value.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter03/Exercise3.3/test-age.php: -------------------------------------------------------------------------------- 1 | 25) { 5 | print("Adult"); 6 | } elseif ($age >= 18) { 7 | print("Young"); 8 | } elseif ($age > 10) { 9 | print("Teenager"); 10 | } else { 11 | print("Child"); 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/templates/home.php: -------------------------------------------------------------------------------- 1 |
2 |

Hello!

3 |

Sign up to start creating your contacts list.

4 |

Already have an account? Login here.

5 |
-------------------------------------------------------------------------------- /Chapter07/Exercise7.13/db-common/connection-no-db.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter02/Exercise2.4/convertintstring.php: -------------------------------------------------------------------------------- 1 | int to string:'; 3 | $number = 1234; 4 | 5 | echo '

Before type conversion:

'; 6 | var_dump($number); 7 | 8 | echo '

After type conversion:

'; 9 | $stringValue = (string) ($number); 10 | var_dump($stringValue); -------------------------------------------------------------------------------- /Chapter07/Exercise7.14/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.15/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.16/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.17/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.18/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.19/db-common/connection.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | ]; 7 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 8 | 9 | return $pdo; 10 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/templates/profile.php: -------------------------------------------------------------------------------- 1 |
2 |

Welcome, !

3 |
4 | 5 |

Session data:

6 |
7 | 8 |
9 | 10 |

Logout

11 | -------------------------------------------------------------------------------- /Chapter02/Activity2.1/tracker.php: -------------------------------------------------------------------------------- 1 | Hello $name, your BMI is $bmi

"; -------------------------------------------------------------------------------- /Chapter07/Exercise7.6/download.php: -------------------------------------------------------------------------------- 1 | $b) { 7 | $difference = $a - $b; 8 | } else { 9 | $difference = $b - $a; 10 | } 11 | print("The difference is $difference"); 12 | } else { 13 | print("The numbers are equal"); 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.9/isset.php: -------------------------------------------------------------------------------- 1 | '; 7 | echo 'checking $name2: '; 8 | var_dump(isset($name2)); 9 | echo '
'; 10 | echo 'checking undeclared variable $name3: '; 11 | echo var_dump(isset($name3)); 12 | ?> -------------------------------------------------------------------------------- /Chapter09/Exercise9.9/index.php: -------------------------------------------------------------------------------- 1 | pushHandler(new StreamHandler('./logs/app.log', Logger::INFO)); 10 | 11 | $e = new Packt\Example($logger); 12 | $e->doSomething(); -------------------------------------------------------------------------------- /Chapter06/Exercise6.10/bootstrap-homepage/web/index.php: -------------------------------------------------------------------------------- 1 | 'My main template', 8 | ]; 9 | 10 | echo $mainTemplate->render($templateData); 11 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.1/custom-handler.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 13 | return ''; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter04/Examples/how-many-times-did-we-tell-you.php: -------------------------------------------------------------------------------- 1 | pushHandler(new StreamHandler('./logs/app.log', Logger::INFO)); 10 | 11 | $e = new Packt\Example($logger); 12 | $e->doSomething(); 13 | 14 | $e->printUuid(); -------------------------------------------------------------------------------- /Chapter08/err-common/error-handler.php: -------------------------------------------------------------------------------- 1 | email = $email; 12 | $this->firstName = $firstName; 13 | $this->lastName = $lastName; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter02/Exercise2.5/activity-height.php: -------------------------------------------------------------------------------- 1 | setTitle('Dr.'); 11 | $professor->printStudents(); -------------------------------------------------------------------------------- /Chapter05/Examples/interface.php: -------------------------------------------------------------------------------- 1 | interface A 2 | { 3 | function a(); 4 | } 5 | 6 | interface B 7 | { 8 | function b(); 9 | } 10 | interface C extends A, B 11 | { 12 | function c(); 13 | } 14 | class D implements C 15 | { 16 | function a(){ 17 | ... 18 | } 19 | function b() 20 | { 21 | ... 22 | } 23 | function c() 24 | { 25 | ... 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/tests/autoload.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 14 | return ''; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter10/Exercise10.3/guzzle-example/ipify.php: -------------------------------------------------------------------------------- 1 | 'https://api.ipify.org']); 7 | 8 | $response = $client->request('GET', '/', [ 9 | 'query' => ['format'=>'json'] 10 | ]); 11 | 12 | $responseObject = json_decode($response->getBody()->getContents()); 13 | 14 | echo "Your public facing ip address is {$responseObject->ip}" . PHP_EOL; -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/tests/autoload.php: -------------------------------------------------------------------------------- 1 | exec($sql) !== false) { 11 | echo "The database '$dbname' was successfully created." . PHP_EOL; 12 | } else { 13 | list(, , $driverErrMsg) = $pdo->errorInfo(); 14 | echo "Error creating the database: $driverErrMsg" . PHP_EOL; 15 | } 16 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/handlers/Logout.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 14 | return ''; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter02/Exercise2.1/order.php: -------------------------------------------------------------------------------- 1 | = 25) { 11 | //change $complete to true to indicate the order is complete 12 | $complete = true; 13 | //display the $str and add the orderTotal 14 | echo $str . $orderTotal; 15 | } -------------------------------------------------------------------------------- /Chapter04/Exercise4.4/count-me-with-GLOBALS.php: -------------------------------------------------------------------------------- 1 | getMessage()); 5 | $line = str_repeat('-', $msgLength); 6 | echo $line, PHP_EOL; 7 | echo $e->getMessage(), PHP_EOL; 8 | echo '> File: ', $e->getFile(), PHP_EOL; 9 | echo '> Line: ', $e->getLine(), PHP_EOL; 10 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 11 | echo $line, PHP_EOL; 12 | }); 13 | -------------------------------------------------------------------------------- /Chapter05/Examples/trait-testing.php: -------------------------------------------------------------------------------- 1 | say(); 26 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.7/err-common/exception-handler.php: -------------------------------------------------------------------------------- 1 | getMessage()); 5 | $line = str_repeat('-', $msgLength); 6 | echo $line, PHP_EOL; 7 | echo $e->getMessage(), PHP_EOL; 8 | echo '> File: ', $e->getFile(), PHP_EOL; 9 | echo '> Line: ', $e->getLine(), PHP_EOL; 10 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 11 | echo $line, PHP_EOL; 12 | }); 13 | -------------------------------------------------------------------------------- /Chapter02/Exercise2.3/convertbooleanint.php: -------------------------------------------------------------------------------- 1 | Boolean to Int'; 3 | $trueValueBool = true; 4 | $falseValueBool = false; 5 | 6 | echo '

Before type conversion:

'; 7 | var_dump($trueValueBool); 8 | echo '
'; 9 | var_dump($falseValueBool); 10 | 11 | echo '

After type conversion:

'; 12 | $trueValueInt = (int) ($trueValueBool); 13 | $falseValueInt = (int) ($falseValueBool); 14 | var_dump($trueValueInt); 15 | echo '
'; 16 | var_dump($falseValueInt); -------------------------------------------------------------------------------- /Chapter07/Exercise7.4/fgets.php: -------------------------------------------------------------------------------- 1 | exec($insertStmt) === false) { 9 | list(, , $driverErrMsg) = $pdo->errorInfo(); 10 | echo "Error inserting into the users table: $driverErrMsg" . PHP_EOL; 11 | return; 12 | } 13 | 14 | echo "Successfully inserted into users table the record with id " . $pdo->lastInsertId() . PHP_EOL; 15 | -------------------------------------------------------------------------------- /Chapter05/Examples/MyClass.php: -------------------------------------------------------------------------------- 1 | say(); //outputs, Overridden! 27 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.2/log-handler.php: -------------------------------------------------------------------------------- 1 | make . PHP_EOL; 8 | echo "Model: " . $vehicle->model . PHP_EOL; 9 | echo "Color: " . $vehicle->color . PHP_EOL; 10 | //echo "No of wheels: " . $vehicle->noOfWheels . PHP_EOL; 11 | //echo "Engine No: " . $vehicle->engineNumber . PHP_EOL; 12 | echo "No of wheels: " . $vehicle->getNoOfWheels() . PHP_EOL; 13 | echo "Engine No: " . $vehicle->getEngineNumber() . PHP_EOL; -------------------------------------------------------------------------------- /Chapter07/Activity7.1/app_users.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO app.users (id, username, password, signup_time) VALUES (1, 'sasha', '$2y$10$tFg9jZuNSi0urO4MbHJw2eGNzZF1TqANY1K8Olg3osLvQsA1mQPmK', '2019-04-07 15:31:20'); 2 | INSERT INTO app.users (id, username, password, signup_time) VALUES (2, 'alex', '$2y$10$CK2tZrjGcYN8xiTkSKwBWeVvZF6dG.abxRDfLGE9cVmFUK9uavX1.', '2019-04-07 16:11:25'); 3 | INSERT INTO app.users (id, username, password, signup_time) VALUES (3, 'alex2', '$2y$10$Hviemw8Y.1ZPdj9Y/L5PEO1Z08rSmSYN71q/q0y7lsW37BmRqdRoG', '2019-04-07 16:12:33'); -------------------------------------------------------------------------------- /Chapter04/Exercise4.5/add.php: -------------------------------------------------------------------------------- 1 | PDO::FETCH_ASSOC, 6 | // PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 7 | ]; 8 | $pdo = new PDO($dsn, "php-user", "php-pass", $options); 9 | 10 | echo sprintf( 11 | "Connected to MySQL server v%s, on %s", 12 | $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), 13 | $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS) 14 | ) . PHP_EOL; 15 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.5/fgetcsv.php: -------------------------------------------------------------------------------- 1 | logger = $logger; 10 | } 11 | 12 | public function doSomething() 13 | { 14 | echo "Something" . PHP_EOL; 15 | 16 | $this->logger->info('This is an informational message'); 17 | $this->logger->error('This message logs an error condition'); 18 | $this->logger->critical('This message logs unexpected exceptions'); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.16/insert-prepared.php: -------------------------------------------------------------------------------- 1 | prepare("INSERT INTO users (email) VALUES (:email)"); 7 | 8 | if ($insertStmt->execute([':email' => $argv[1] ?? null]) === false) { 9 | list(, , $driverErrMsg) = $insertStmt->errorInfo(); 10 | echo "Error inserting into the users table: $driverErrMsg" . PHP_EOL; 11 | return; 12 | } 13 | 14 | echo "Successfully inserted into users table the record with id " . $pdo->lastInsertId() . PHP_EOL; 15 | -------------------------------------------------------------------------------- /Chapter05/Examples/Class-hints.php: -------------------------------------------------------------------------------- 1 | name = $name; 12 | $this->mailer = $mailer; 13 | $this->database = $db; 14 | } 15 | } 16 | class Mailer 17 | { 18 | 19 | } 20 | class Database 21 | { 22 | 23 | } 24 | $mailer = new Mailer(); 25 | $database = new Database(); 26 | $user = new User('John Doe', $mailer, $database); -------------------------------------------------------------------------------- /Chapter03/Exercise3.9/print-professions-subjects.php: -------------------------------------------------------------------------------- 1 | '; 5 | $animal1 = 'Cat'; 6 | $animal2 = $animal1; 7 | echo $animal1 . ' - ' . $animal2; 8 | echo '
'; 9 | $animal2 = 'Dog'; 10 | echo $animal1 . ' - ' . $animal2; 11 | echo '
'; 12 | // Assignment by reference 13 | echo 'Assignment by reference'; 14 | echo '
'; 15 | $animal3 = 'Elephant'; 16 | $animal4 = &$animal3; 17 | echo $animal3 . ' - ' . $animal4; 18 | echo '
'; 19 | $animal4 = 'Giraffe'; 20 | echo $animal3 . ' - ' . $animal4; 21 | ?> -------------------------------------------------------------------------------- /Chapter06/Exercise6.8/output-escape-reflected.php: -------------------------------------------------------------------------------- 1 | You have searched for: %s

', htmlentities($_GET['s'])); 5 | } else { 6 | echo "Use the form to start searching."; 7 | } 8 | ?> 9 | 10 |
11 | 12 | 13 | 14 |
15 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.11/copy.php: -------------------------------------------------------------------------------- 1 | protectedMember;//fatal error -------------------------------------------------------------------------------- /Chapter04/Exercise4.3/array-functions.php: -------------------------------------------------------------------------------- 1 | name = $name; 11 | $this->mailer = $mailer; 12 | $this->database = $db; 13 | } 14 | } 15 | class Mailer 16 | { 17 | //class body 18 | } 19 | class Database 20 | { 21 | //class body 22 | } 23 | $mailer = new Mailer(); 24 | $database = new Database(); 25 | $user = new User('John Doe', $mailer, $database); 26 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/handlers/Profile.php: -------------------------------------------------------------------------------- 1 | handle(); 14 | } 15 | return (new Template('profile'))->render(); 16 | } 17 | 18 | public function getTitle(): string 19 | { 20 | return 'Profile - ' . parent::getTitle(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.3/fread-memory.php: -------------------------------------------------------------------------------- 1 | exec($createStmt) === false) { 14 | list(, , $driverErrMsg) = $pdo->errorInfo(); 15 | echo "Error creating the users table: $driverErrMsg" . PHP_EOL; 16 | return; 17 | } 18 | 19 | echo "The users table was successfully created."; 20 | -------------------------------------------------------------------------------- /Chapter05/Examples/method-overloading.php: -------------------------------------------------------------------------------- 1 | showMagic('object context', 'second argument'); 22 | $object->showMagic('object context', 'second argument', 'third argument'); 23 | MyMagicMethodClass::showMagic('static context'); 24 | -------------------------------------------------------------------------------- /Chapter04/Examples/function-average.php: -------------------------------------------------------------------------------- 1 | hello(); 21 | 22 | use function MyNamespaceA\myFunction;//importing a function 23 | myFunction();//calls MyNamespaceA\myFunction 24 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.18/update.php: -------------------------------------------------------------------------------- 1 | prepare("UPDATE users SET email = :email WHERE id = :id"); 9 | 10 | if ($updateStmt->execute([':id' => $updateId, ':email' => $updateEmail]) === false) { 11 | list(, , $driverErrMsg) = $updateStmt->errorInfo(); 12 | echo "Error running the query: $driverErrMsg" . PHP_EOL; 13 | return; 14 | } 15 | 16 | echo sprintf("The query ran successfully. %d row(s) were affected.", $updateStmt->rowCount()) . PHP_EOL; 17 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.4/on-shutdown.php: -------------------------------------------------------------------------------- 1 | 'Spiderman', 5 | 'weapon' => 'Spider web' 6 | ], 7 | [ 8 | 'heroName' => 'Iron Man', 9 | 'weapon' => 'Mark L' 10 | ], 11 | [ 12 | 'heroName' => 'Thor', 13 | 'weapon' => 'Mjolnir' 14 | ], 15 | [ 16 | 'heroName' => 'Captain America', 17 | 'weapon' => 'Shield' 18 | ] 19 | ]; 20 | echo '
';
21 | print_r($heroInfo);
22 | echo '
';
23 | 
24 | echo 'The weapon of choice for ' . $heroInfo[3]['heroName'] . ' is ' .
25 | $heroInfo[3]['weapon'];
26 | echo '
'; 27 | echo $heroInfo[2]['heroName'] . ' wields ' . $heroInfo[2]['weapon']; -------------------------------------------------------------------------------- /Chapter09/Exercise9.9/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mmccollum/composer-example", 3 | "description": "A simple example of using composer functionality", 4 | "type": "project", 5 | "authors": [ 6 | { 7 | "name": "Mark McCollum", 8 | "email": "mark@example.com" 9 | } 10 | ], 11 | "minimum-stability": "stable", 12 | "require": { 13 | "monolog/monolog": "^1.24" 14 | }, 15 | "require-dev": { 16 | "phpunit/phpunit": "^8.0" 17 | }, 18 | "autoload": { 19 | "psr-4": { 20 | "Packt\\": "src/Packt/" 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter01/Examples/Example1.01.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | My First PHP Page 8 | 9 | 10 |
11 |

The Heading

12 |

13 | 16 |

17 |
18 | 19 | 20 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.3/Motorcycle.php: -------------------------------------------------------------------------------- 1 | make . PHP_EOL; 14 | echo " Model: " . $motorcycle->model . PHP_EOL; 15 | echo " Color: " . $motorcycle->color . PHP_EOL; 16 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 17 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 18 | -------------------------------------------------------------------------------- /Chapter09/Exercise9.2/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mmccollum/composer-example", 3 | "description": "A simple example of using composer functionality", 4 | "type": "project", 5 | "authors": [ 6 | { 7 | "name": "Mark McCollum", 8 | "email": "mark@example.com" 9 | } 10 | ], 11 | "minimum-stability": "stable", 12 | "require": { 13 | "monolog/monolog": "^1.24" 14 | }, 15 | "require-dev": { 16 | "phpunit/phpunit": "^8.0" 17 | }, 18 | "autoload": { 19 | "psr-4": { 20 | "Packt\\": "src/Packt/" 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter07/db-common/singleton.php: -------------------------------------------------------------------------------- 1 | pdo = new PDO(...); 8 | } 9 | 10 | public static function instance() 11 | { 12 | static $instance; 13 | if (is_null($instance)) { 14 | $instance = new static; 15 | } 16 | return $instance; 17 | } 18 | } 19 | 20 | $databaseSingleton1 = DatabaseSingleton::instance(); 21 | $databaseSingleton2 = DatabaseSingleton::instance(); 22 | 23 | echo "Same class instance? ", 24 | $databaseSingleton1 === $databaseSingleton2 ? 'YES' : 'NO', 25 | PHP_EOL; 26 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/src/handlers/Handler.php: -------------------------------------------------------------------------------- 1 | redirectUri = $uri; 19 | header("Location: $uri", true); 20 | } 21 | 22 | public function willRedirect(): bool 23 | { 24 | return strlen($this->redirectUri) > 0; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/handlers/Handler.php: -------------------------------------------------------------------------------- 1 | redirectUri = $uri; 20 | header("Location: $uri", true); 21 | } 22 | 23 | public function willRedirect(): bool 24 | { 25 | return strlen($this->redirectUri) > 0; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter07/Example/DatabaseSingleton.php: -------------------------------------------------------------------------------- 1 | pdo = new PDO(...); 8 | } 9 | 10 | public static function instance() 11 | { 12 | static $instance; 13 | if (is_null($instance)) { 14 | $instance = new static; 15 | } 16 | return $instance; 17 | } 18 | } 19 | 20 | $databaseSingleton1 = DatabaseSingleton::instance(); 21 | $databaseSingleton2 = DatabaseSingleton::instance(); 22 | 23 | echo "Same class instance? ", 24 | $databaseSingleton1 === $databaseSingleton2 ? 'YES' : 'NO', 25 | PHP_EOL; 26 | -------------------------------------------------------------------------------- /Chapter03/Exercise3.4/test-datatype.php: -------------------------------------------------------------------------------- 1 | handle(); 12 | } 13 | return (new \Components\Template('profile'))->render([ 14 | 'username' => $_SESSION['username'], 15 | 'sessionData' => var_export($_SESSION, true), 16 | ]); 17 | } 18 | 19 | public function getTitle(): string 20 | { 21 | return 'Profile - ' . parent::getTitle(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/autoload.php: -------------------------------------------------------------------------------- 1 | logger = $logger; 15 | } 16 | 17 | public function doSomething() 18 | { 19 | echo "Something" . PHP_EOL; 20 | 21 | $this->logger->info('This is an informational message'); 22 | $this->logger->error('This message logs an error condition'); 23 | $this->logger->critical('This message logs unexpected exceptions'); 24 | } 25 | 26 | public function printUuid(): void 27 | { 28 | $uuid = Uuid::uuid1(); 29 | echo $uuid . PHP_EOL; 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter08/Activity8.1/tests/Tests/PrintTest.php: -------------------------------------------------------------------------------- 1 | expectOutputString("(!) $message\n"); 14 | printError($message); 15 | } 16 | 17 | public function testPrintHello() 18 | { 19 | $message = 'Hello'; 20 | $this->expectOutputString("(!) $message\n"); 21 | printError($message); 22 | } 23 | 24 | public function testPrintThrowException() 25 | { 26 | $message = []; 27 | $this->expectException(\TypeError::class); 28 | printError($message); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.5/basic-try.php: -------------------------------------------------------------------------------- 1 | getMessage(), $e->getFile(), $e->getLine()), PHP_EOL; 19 | 20 | } finally { 21 | 22 | echo "FINALLY block gets executed.\n"; 23 | 24 | } 25 | 26 | echo "Outside TRY-CATCH.\n"; 27 | 28 | echo 'SCRIPT END.', PHP_EOL; 29 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/templates/profile.php: -------------------------------------------------------------------------------- 1 | 7 | 8 |
9 |

Welcome, getUsername() ?>!

10 |
11 |

Your profile:

12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
Username:getUsername() ?>
Signup date:getSignupTime()->format(DATE_RSS) ?>
Last login:format(DATE_RSS) ?>
28 |
29 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.19/delete.php: -------------------------------------------------------------------------------- 1 | prepare("DELETE FROM users WHERE email LIKE :partialMatch"); 8 | 9 | if ($deleteStmt->execute([':partialMatch' => "%$partialMatch%"]) === false) { 10 | list(, , $driverErrMsg) = $deleteStmt->errorInfo(); 11 | echo "Error deleting from the users table: $driverErrMsg" . PHP_EOL; 12 | return; 13 | } 14 | 15 | if($rowCount = $deleteStmt->rowCount()){ 16 | echo sprintf("Successfully deleted %d records matching '%s' from users table.", $rowCount, $partialMatch) . PHP_EOL; 17 | } else { 18 | echo sprintf("No records matching '%s' were found in users table.", $partialMatch) . PHP_EOL; 19 | } 20 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.7/basic-try-handler.php: -------------------------------------------------------------------------------- 1 | getMessage(), $e->getFile(), $e->getLine()), PHP_EOL; 21 | 22 | } finally { 23 | 24 | echo "FINALLY block gets executed.\n"; 25 | 26 | } 27 | 28 | echo "Outside TRY-CATCH.\n"; 29 | 30 | echo 'SCRIPT END.', PHP_EOL; 31 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.2/vehicle-objects.php: -------------------------------------------------------------------------------- 1 | getMake() . PHP_EOL; 8 | echo "Model: " . $vehicle->getModel() . PHP_EOL; 9 | echo "Color: " . $vehicle->getColor() . PHP_EOL; 10 | echo "No of wheels: " . $vehicle->getNoOfWheels() . PHP_EOL; 11 | echo "Engine No: " . $vehicle->getEngineNumber() . PHP_EOL . PHP_EOL; 12 | 13 | $vehicle1 = new Vehicle('Honda', 'Civic', 'Red', 4, '23CJ4567'); 14 | echo "Make: " . $vehicle1->getMake() . PHP_EOL; 15 | echo "Model: " . $vehicle1->getModel() . PHP_EOL; 16 | echo "Color: " . $vehicle1->getColor() . PHP_EOL; 17 | echo "No of wheels: " . $vehicle1->getNoOfWheels() . PHP_EOL; 18 | echo "Engine No: " . $vehicle1->getEngineNumber() . PHP_EOL; -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/handlers/Handler.php: -------------------------------------------------------------------------------- 1 | redirectUri = $uri; 19 | header("Location: $uri", true); 20 | } 21 | 22 | public function requestRefresh() 23 | { 24 | $this->requestRedirect($_SERVER['REQUEST_URI']); 25 | } 26 | 27 | public function willRedirect(): bool 28 | { 29 | return strlen($this->redirectUri) > 0; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/src/components/Template.php: -------------------------------------------------------------------------------- 1 | name = $name; 14 | } 15 | 16 | private function getFilepath(): string 17 | { 18 | return self::$viewsPath . DIRECTORY_SEPARATOR . $this->name . '.php'; 19 | } 20 | 21 | function render(array $data = []): string 22 | { 23 | extract($data, EXTR_OVERWRITE); 24 | ob_start(); 25 | require $this->getFilepath(); 26 | $rendered = ob_get_clean(); 27 | return (string)$rendered; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/components/Template.php: -------------------------------------------------------------------------------- 1 | name = $name; 14 | } 15 | 16 | private function getFilepath(): string 17 | { 18 | return self::$viewsPath . DIRECTORY_SEPARATOR . $this->name . '.php'; 19 | } 20 | 21 | function render(array $data = []): string 22 | { 23 | extract($data, EXTR_OVERWRITE); 24 | ob_start(); 25 | require $this->getFilepath(); 26 | $rendered = ob_get_clean(); 27 | return (string)$rendered; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/components/Template.php: -------------------------------------------------------------------------------- 1 | name = $name; 14 | } 15 | 16 | private function getFilepath(): string 17 | { 18 | return self::$viewsPath . DIRECTORY_SEPARATOR . $this->name . '.php'; 19 | } 20 | 21 | function render(array $data = []): string 22 | { 23 | extract($data, EXTR_OVERWRITE); 24 | ob_start(); 25 | require $this->getFilepath(); 26 | $rendered = ob_get_clean(); 27 | return (string)$rendered; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.10/bootstrap-homepage/src/components/Template.php: -------------------------------------------------------------------------------- 1 | name = $name; 15 | } 16 | 17 | private function getFilepath(): string 18 | { 19 | return self::$viewsPath . DIRECTORY_SEPARATOR . $this->name . '.php'; 20 | } 21 | 22 | function render(array $data = []): string 23 | { 24 | extract($data, EXTR_OVERWRITE); 25 | ob_start(); 26 | require $this->getFilepath(); 27 | $rendered = ob_get_clean(); 28 | return (string)$rendered; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.3/Car.php: -------------------------------------------------------------------------------- 1 | getMake() . PHP_EOL; 18 | echo " Model: " . $car->getModel() . PHP_EOL; 19 | echo " Color: " . $car->getColor() . PHP_EOL; 20 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 21 | 22 | echo " No of Doors: " . $car->doors . PHP_EOL; 23 | echo " Transmission: " . $car->transmission . PHP_EOL; 24 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; -------------------------------------------------------------------------------- /Chapter01/Activity1.1/movies.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | <?php echo $name; ?> 13 | 14 | 15 |
16 |

Information about

17 |

18 | Based on the input, here is the information so far: 19 |
20 | 21 |

22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /Chapter05/Activity5.1/Professor/Professor.php: -------------------------------------------------------------------------------- 1 | name = $name; 14 | 15 | foreach ($students as $student) { 16 | if ($student instanceof Student) { 17 | $this->students[] = $student; 18 | } 19 | } 20 | } 21 | 22 | public function setTitle(string $title) 23 | { 24 | $this->title = $title; 25 | } 26 | 27 | public function printStudents() 28 | { 29 | echo "$this->title $this->name's students (" .count($this->students). "): " . PHP_EOL; 30 | 31 | $serial = 1; 32 | foreach ($this->students as $student) { 33 | echo " $serial. $student->name " . PHP_EOL; 34 | $serial++; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Chapter08/Exercise8.5/basic-try-all.php: -------------------------------------------------------------------------------- 1 | getMessage(), $e->getFile(), $e->getLine()), PHP_EOL; 19 | 20 | } catch (Error $e) { 21 | 22 | echo 'ERROR: ', sprintf('%s in %s at line %d', $e->getMessage(), $e->getFile(), $e->getLine()), PHP_EOL; 23 | 24 | } finally { 25 | 26 | echo "FINALLY block gets executed.\n"; 27 | 28 | } 29 | 30 | echo "Outside TRY-CATCH.\n"; 31 | 32 | echo 'SCRIPT END.', PHP_EOL; 33 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.2/super-cookie.php: -------------------------------------------------------------------------------- 1 | The referral code [%s] was stored in a cookie. ' . 6 | 'Reload the page to see the cookie value above. ' . 7 | 'Clear the query string.

', $_GET['refcode']); 8 | } else { 9 | echo sprintf('

No referral code was set in query string.

'); 10 | } 11 | 12 | echo sprintf( 13 | '

Referral code (sent by browser as cookie): [%s]

', 14 | array_key_exists('ref', $_COOKIE) ? $_COOKIE['ref'] : '-None-' 15 | ); 16 | 17 | ?> 18 | 19 |
20 | 21 | 22 |
23 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/db/setUp.sql: -------------------------------------------------------------------------------- 1 | -- contacts: table 2 | CREATE TABLE IF NOT EXISTS `contacts` 3 | ( 4 | `id` int(11) NOT NULL AUTO_INCREMENT, 5 | `user_id` int(11) NOT NULL, 6 | `name` varchar(100) NOT NULL, 7 | `phone` varchar(50) DEFAULT NULL, 8 | `email` varchar(254) DEFAULT NULL, 9 | `address` varchar(255) DEFAULT NULL, 10 | PRIMARY KEY (`id`) 11 | ) ENGINE = InnoDB 12 | DEFAULT CHARSET = utf8mb4; 13 | 14 | -- users: table 15 | CREATE TABLE IF NOT EXISTS `users` 16 | ( 17 | `id` int(11) NOT NULL AUTO_INCREMENT, 18 | `username` varchar(150) NOT NULL, 19 | `password` char(60) NOT NULL, 20 | `signup_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, 21 | PRIMARY KEY (`id`), 22 | UNIQUE KEY `users_username_uindex` (`username`) 23 | ) ENGINE = InnoDB 24 | DEFAULT CHARSET = utf8mb4; 25 | 26 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.7/write.php: -------------------------------------------------------------------------------- 1 | Successfully written %d bytes to [%s] with fwrite():", $written, $fileFwrite) . PHP_EOL; 11 | fseek($fp, 0); 12 | echo fread($fp, filesize($fileFwrite)) . PHP_EOL; 13 | } 14 | 15 | $fileFpc = 'sample/write-with-fpc.txt'; 16 | $written = file_put_contents($fileFpc, 'File written with file_put_contents().' . PHP_EOL); 17 | 18 | if (false === $written) { 19 | echo 'Error writing with fwrite.' . PHP_EOL; 20 | } else { 21 | echo sprintf("> Successfully written %d bytes to [%s] with file_put_contents():", $written, $fileFpc) . PHP_EOL; 22 | echo file_get_contents($fileFpc) . PHP_EOL; 23 | } 24 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.4/Car.php: -------------------------------------------------------------------------------- 1 | getMake() . PHP_EOL; 18 | echo " Model: " . $car->getModel() . PHP_EOL; 19 | echo " Color: " . $car->getColor() . PHP_EOL; 20 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 21 | 22 | echo " No of Doors: " . $car->doors . PHP_EOL; 23 | echo " Transmission: " . $car->transmission . PHP_EOL; 24 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 25 | 26 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 27 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 28 | -------------------------------------------------------------------------------- /Chapter05/Examples/MyMagicMethodClass.php: -------------------------------------------------------------------------------- 1 | showMagic('object context', 'second argument'); 15 | $object->showMagic('object context', 'second argument', 'third argument'); 16 | MyMagicMethodClass::showMagic('static context'); 17 | /* 18 | outputs, 19 | array(2) { 20 | [0]=> 21 | string(14) "object context" 22 | [1]=> 23 | string(15) "second argument" 24 | } 25 | array(3) { 26 | [0]=> 27 | string(14) "object context" 28 | [1]=> 29 | string(15) "second argument" 30 | [2]=> 31 | string(14) "third argument" 32 | } 33 | array(1) { 34 | [0]=> 35 | string(14) "static context" 36 | } 37 | */ 38 | -------------------------------------------------------------------------------- /Chapter05/Examples/Person.php: -------------------------------------------------------------------------------- 1 | name = $username; 8 | } 9 | function getName() 10 | { 11 | return $this->name; 12 | } 13 | function setName() 14 | { 15 | $this->name = 'Jhon Doe'; 16 | } 17 | function sayGreetings() 18 | { 19 | if(date('G') < 12) 20 | { 21 | $greetings = 'Good Morning'; 22 | } 23 | elseif(date('G') < 17) 24 | { 25 | $greetings = 'Good Afternoon'; 26 | } 27 | else 28 | { 29 | $greetings = 'Good Evening'; 30 | } 31 | echo "$greetings $this->name! "; 32 | } 33 | 34 | function __destruct() 35 | { 36 | echo 'The object has been removed.'; 37 | } 38 | 39 | } 40 | 41 | $person1 = new Person('John Doe'); 42 | $person2 = new Person('Jen Doe'); 43 | 44 | echo $person1->name . PHP_EOL; //prints John Doe 45 | echo $person2->name . PHP_EOL; //prints Jen Doe 46 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/web/index.php: -------------------------------------------------------------------------------- 1 | 'My main template', 15 | ]; 16 | 17 | $router = new \Components\Router(); 18 | if ($handler = $router->getHandler()) { 19 | $content = $handler->handle(); 20 | if ($handler->willRedirect()) { 21 | return; 22 | } 23 | $templateData['content'] = $content; 24 | $templateData['title'] = $handler->getTitle(); 25 | } 26 | 27 | echo $mainTemplate->render($templateData); 28 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.8/write-append.php: -------------------------------------------------------------------------------- 1 | Successfully written %d bytes to [%s] with fwrite():", $written, $fileFwrite) . PHP_EOL; 11 | fseek($fp, 0); 12 | echo fread($fp, filesize($fileFwrite)) . PHP_EOL; 13 | } 14 | 15 | $fileFpc = 'sample/write-with-fpc.txt'; 16 | $written = file_put_contents($fileFpc, 'File written with file_put_contents().' . PHP_EOL, FILE_APPEND); 17 | 18 | if (false === $written) { 19 | echo 'Error writing with fwrite.' . PHP_EOL; 20 | } else { 21 | echo sprintf("> Successfully written %d bytes to [%s] with file_put_contents():", $written, $fileFpc) . PHP_EOL; 22 | echo file_get_contents($fileFpc) . PHP_EOL; 23 | } 24 | -------------------------------------------------------------------------------- /Chapter10/Activity10.1/httpbin.php: -------------------------------------------------------------------------------- 1 | 'http://httpbin.org/']); 8 | 9 | try 10 | { 11 | $response = $client->request('POST', '/response-headers', [ 12 | 'headers' => [ 13 | 'Accept' => 'application-json' 14 | ], 15 | 'query' => [ 16 | 'first' => 'John', 17 | 'last' => 'Doe' 18 | ] 19 | ]); 20 | 21 | if ($response->getStatusCode() !== 200) { 22 | throw new Exception("Status code was {$response->getStatusCode()}, not 200"); 23 | } 24 | 25 | $responseObject = json_decode($response->getBody()->getContents()); 26 | 27 | echo "The web service responded with {$responseObject->first} {$responseObject->last}" . PHP_EOL; 28 | } 29 | catch (Exception $ex) 30 | { 31 | echo "An error occurred: " . $ex->getMessage() . PHP_EOL; 32 | } -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/web/index.php: -------------------------------------------------------------------------------- 1 | 'My main template', 16 | ]; 17 | 18 | $router = new \Components\Router(); 19 | if ($handler = $router->getHandler()) { 20 | $content = $handler->handle(); 21 | if ($handler->willRedirect()) { 22 | return; 23 | } 24 | $templateData['content'] = $content; 25 | $templateData['title'] = $handler->getTitle(); 26 | } 27 | 28 | echo $mainTemplate->render($templateData); 29 | -------------------------------------------------------------------------------- /Chapter08/err-common/all-errors-handler.php: -------------------------------------------------------------------------------- 1 | getCode(), $e->getMessage()); 5 | $msgLength = mb_strlen($message); 6 | $line = str_repeat('-', $msgLength); 7 | echo $line, PHP_EOL; 8 | echo $message, PHP_EOL; 9 | echo '> File: ', $e->getFile(), PHP_EOL; 10 | echo '> Line: ', $e->getLine(), PHP_EOL; 11 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 12 | echo $line, PHP_EOL; 13 | }; 14 | 15 | $errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) { 16 | $exception = new ErrorException($message, $code, $code, $file, $line); 17 | $exceptionHandler($exception); 18 | if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) { 19 | exit(1); 20 | } 21 | }; 22 | 23 | set_error_handler($errorHandler); 24 | set_exception_handler($exceptionHandler); 25 | -------------------------------------------------------------------------------- /Chapter08/Activity8.1/tests/function/factorial.php: -------------------------------------------------------------------------------- 1 | getCode(), $e->getMessage()); 5 | $msgLength = mb_strlen($message); 6 | $line = str_repeat('-', $msgLength); 7 | echo $line, PHP_EOL; 8 | echo $message, PHP_EOL; 9 | echo '> File: ', $e->getFile(), PHP_EOL; 10 | echo '> Line: ', $e->getLine(), PHP_EOL; 11 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 12 | echo $line, PHP_EOL; 13 | }; 14 | 15 | $errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) { 16 | $exception = new ErrorException($message, $code, $code, $file, $line); 17 | $exceptionHandler($exception); 18 | if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) { 19 | exit(1); 20 | } 21 | }; 22 | 23 | set_error_handler($errorHandler); 24 | set_exception_handler($exceptionHandler); 25 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.8/err-common/all-errors-handler.php: -------------------------------------------------------------------------------- 1 | getCode(), $e->getMessage()); 5 | $msgLength = mb_strlen($message); 6 | $line = str_repeat('-', $msgLength); 7 | echo $line, PHP_EOL; 8 | echo $message, PHP_EOL; 9 | echo '> File: ', $e->getFile(), PHP_EOL; 10 | echo '> Line: ', $e->getLine(), PHP_EOL; 11 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 12 | echo $line, PHP_EOL; 13 | }; 14 | 15 | $errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) { 16 | $exception = new ErrorException($message, $code, $code, $file, $line); 17 | $exceptionHandler($exception); 18 | if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) { 19 | exit(1); 20 | } 21 | }; 22 | 23 | set_error_handler($errorHandler); 24 | set_exception_handler($exceptionHandler); 25 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.9/err-common/all-errors-handler.php: -------------------------------------------------------------------------------- 1 | getCode(), $e->getMessage()); 5 | $msgLength = mb_strlen($message); 6 | $line = str_repeat('-', $msgLength); 7 | echo $line, PHP_EOL; 8 | echo $message, PHP_EOL; 9 | echo '> File: ', $e->getFile(), PHP_EOL; 10 | echo '> Line: ', $e->getLine(), PHP_EOL; 11 | echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL; 12 | echo $line, PHP_EOL; 13 | }; 14 | 15 | $errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) { 16 | $exception = new ErrorException($message, $code, $code, $file, $line); 17 | $exceptionHandler($exception); 18 | if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) { 19 | exit(1); 20 | } 21 | }; 22 | 23 | set_error_handler($errorHandler); 24 | set_exception_handler($exceptionHandler); 25 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.5/Motorcycle.php: -------------------------------------------------------------------------------- 1 | make . PHP_EOL; 15 | echo " Model: " . $motorcycle->model . PHP_EOL; 16 | echo " Color: " . $motorcycle->color . PHP_EOL; 17 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 18 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 19 | */ 20 | 21 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 22 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 23 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 24 | echo "Available motorcycles are " . Motorcycle::$counter. PHP_EOL; 25 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.9/run.php: -------------------------------------------------------------------------------- 1 | getMessage(), PHP_EOL; 30 | exit(1); 31 | } 32 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/structure.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA IF NOT EXISTS app; 2 | 3 | USE app; 4 | 5 | -- contacts: table 6 | CREATE TABLE `contacts` 7 | ( 8 | `id` int(11) NOT NULL AUTO_INCREMENT, 9 | `user_id` int(11) NOT NULL, 10 | `name` varchar(100) NOT NULL, 11 | `phone` varchar(50) DEFAULT NULL, 12 | `email` varchar(254) DEFAULT NULL, 13 | `address` varchar(255) DEFAULT NULL, 14 | PRIMARY KEY (`id`) 15 | ) ENGINE = InnoDB 16 | AUTO_INCREMENT = 3 17 | DEFAULT CHARSET = utf8mb4; #latin1 18 | 19 | -- users: table 20 | CREATE TABLE `users` 21 | ( 22 | `id` int(11) NOT NULL AUTO_INCREMENT, 23 | `username` varchar(150) NOT NULL, 24 | `password` char(60) NOT NULL, 25 | `signup_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, 26 | PRIMARY KEY (`id`), 27 | UNIQUE KEY `users_username_uindex` (`username`) 28 | ) ENGINE = InnoDB 29 | AUTO_INCREMENT = 4 30 | DEFAULT CHARSET = utf8mb4; #latin1 31 | 32 | -------------------------------------------------------------------------------- /Chapter07/Exercise7.10/move.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 29 | return ''; 30 | } 31 | }; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/components/Router.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 30 | return ''; 31 | } 32 | }; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.3/sqrt.php: -------------------------------------------------------------------------------- 1 | NULL,'anotherAttribute' => NULL); 7 | 8 | 9 | public function __set($attribute, $value) 10 | { 11 | if (array_key_exists($attribute, $this->arr)) { 12 | $this->arr[$attribute] = $value; 13 | } else { 14 | echo 'Error: the attribute is not allowed. '; 15 | } 16 | } 17 | 18 | public function __get($attribute) 19 | { 20 | if (array_key_exists($attribute, $this->arr)) { 21 | return $this->arr[$attribute]; 22 | } else { 23 | echo 'Error: undefined attribute. '; 24 | } 25 | } 26 | 27 | } 28 | 29 | 30 | $object = new MyMagicClass(); 31 | $object->dynamicAttribute = 'I am magic'; 32 | echo $object->dynamicAttribute . PHP_EOL; 33 | 34 | $object->testAttribute = 'test'; //outputs, Error: the attribute is not allowed. 35 | echo $object->testAttribute . PHP_EOL; //outputs, Error: undefined attribute. 36 | -------------------------------------------------------------------------------- /Chapter05/Examples/MyMagicClass.php: -------------------------------------------------------------------------------- 1 | NULL,'anotherAttribute' => NULL); 5 | public function __set($attribute, $value) 6 | { 7 | if (array_key_exists($attribute, $this->arr)) 8 | { 9 | $this->arr[$attribute] = $value; 10 | } 11 | else 12 | { 13 | echo 'Error: the attribute is not allowed. '; 14 | } 15 | } 16 | public function __get($attribute) 17 | { 18 | if (array_key_exists($attribute, $this->arr)) 19 | { 20 | return $this->arr[$attribute]; 21 | } 22 | else 23 | { 24 | echo 'Error: undefined attribute. '; 25 | } 26 | } 27 | } 28 | $object = new MyMagicClass(); 29 | $object->dynamicAttribute = 'I am magic'; 30 | echo $object->dynamicAttribute . PHP_EOL; 31 | $object->testAttribute = 'test'; //outputs, Error: the attribute is not allowed. 32 | echo $object->testAttribute . PHP_EOL; //outputs, Error: undefined attribute. 33 | -------------------------------------------------------------------------------- /Chapter01/Exercise1.5/login-form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Login form 5 | 7 | 9 | 10 | 11 |
12 |
13 |
14 |

Authenticate

15 |
16 |
17 | 18 | 20 |
21 |
22 | 23 | 25 |
26 | 28 |
29 |
30 | 31 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/tests/Tests/TemplateTest.php: -------------------------------------------------------------------------------- 1 | getFilepath(); 15 | }); 16 | $filepath = $closure->call($template); 17 | $this->assertSame(sprintf('%s%s%s', $template::$viewsPath, DIRECTORY_SEPARATOR, 'main.php'), $filepath); 18 | } 19 | 20 | public function testRender() 21 | { 22 | Template::$viewsPath = __DIR__ . '/../views'; 23 | $template = new Template('testView'); 24 | 25 | $output = $template->render(); 26 | $this->assertSame('

Name is Unknown

', trim($output)); 27 | 28 | $output = $template->render(['name' => 'A-Bomb (HAS)']); 29 | $this->assertSame('

Name is A-Bomb (HAS)

', trim($output)); 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/tests/Tests/TemplateTest.php: -------------------------------------------------------------------------------- 1 | getFilepath(); 15 | }); 16 | $filepath = $closure->call($template); 17 | $this->assertSame(sprintf('%s%s%s', $template::$viewsPath, DIRECTORY_SEPARATOR, 'main.php'), $filepath); 18 | } 19 | 20 | public function testRender() 21 | { 22 | Template::$viewsPath = __DIR__ . '/../views'; 23 | $template = new Template('testView'); 24 | 25 | $output = $template->render(); 26 | $this->assertSame('

Name is Unknown

', trim($output)); 27 | 28 | $output = $template->render(['name' => 'A-Bomb (HAS)']); 29 | $this->assertSame('

Name is A-Bomb (HAS)

', trim($output)); 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter06/Exercise6.10/bootstrap-homepage/tests/Tests/TemplateTest.php: -------------------------------------------------------------------------------- 1 | getFilepath(); 15 | }); 16 | $filepath = $closure->call($template); 17 | $this->assertSame(sprintf('%s%s%s', $template::$viewsPath, DIRECTORY_SEPARATOR, 'main.php'), $filepath); 18 | } 19 | 20 | public function testRender() 21 | { 22 | Template::$viewsPath = __DIR__ . '/../views'; 23 | $template = new Template('testView'); 24 | 25 | $output = $template->render(); 26 | $this->assertSame('

Name is Unknown

', trim($output)); 27 | 28 | $output = $template->render(['name' => 'A-Bomb (HAS)']); 29 | $this->assertSame('

Name is A-Bomb (HAS)

', trim($output)); 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/Tests/TemplateTest.php: -------------------------------------------------------------------------------- 1 | getFilepath(); 16 | }); 17 | $filepath = $closure->call($template); 18 | $this->assertSame(sprintf('%s%s%s', $template::$viewsPath, DIRECTORY_SEPARATOR, 'main.php'), $filepath); 19 | } 20 | 21 | public function testRender() 22 | { 23 | Template::$viewsPath = __DIR__ . '/../views'; 24 | $template = new Template('testView'); 25 | 26 | $output = $template->render(); 27 | $this->assertSame('

Name is Unknown

', trim($output)); 28 | 29 | $output = $template->render(['name' => 'A-Bomb (HAS)']); 30 | $this->assertSame('

Name is A-Bomb (HAS)

', trim($output)); 31 | } 32 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Packt Workshops 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Chapter04/Exercise4.8/activity-functions.php: -------------------------------------------------------------------------------- 1 | [ 4 | 'ET', 5 | 'Raiders of the lost ark', 6 | 'Saving Private Ryan' 7 | ], 8 | 'martin-scorsese' => [ 9 | 'Ashes and Diamonds', 10 | 'The Leopard', 11 | 'The River' 12 | ], 13 | 'kathryn-bigelow' => [ 14 | 'Detroit', 15 | 'Last Days', 16 | 'The Hurt Locker' 17 | ], 18 | 'felix-gary-gray' => [ 19 | 'Men in Black: International', 20 | 'The Fate of the Furious', 21 | 'Law Abiding Citizen' 22 | ] 23 | ]; 24 | function processDirectorName($name){ 25 | $nameParts = explode('-', $name); 26 | $firstname = ucfirst($nameParts[0]); 27 | $lastname = strtoupper($nameParts[1]); 28 | return "$firstname $lastname"; 29 | } 30 | 31 | function processMovies($movies) 32 | { 33 | $formattedStrings = []; 34 | for ($i = 0; $i < count($movies); $i++) { 35 | $formattedStrings[] = '"' . strtoupper($movies[$i]) . '"'; 36 | } 37 | return implode(",", $formattedStrings); 38 | } 39 | 40 | ksort($directors); 41 | foreach ($directors as $key => $value) { 42 | echo processDirectorName($key) . ": "; 43 | echo processMovies($value); 44 | echo PHP_EOL; 45 | } -------------------------------------------------------------------------------- /Chapter07/Exercise7.17/select-all.php: -------------------------------------------------------------------------------- 1 | query($statement); 9 | if ($result === false) { 10 | list(, , $driverErrMsg) = $pdo->errorInfo(); 11 | echo "Error querying the users table: $driverErrMsg" . PHP_EOL; 12 | return; 13 | } 14 | 15 | echo "All records" . PHP_EOL; 16 | while ($record = $result->fetch()) { 17 | echo implode("\t", $record) . PHP_EOL; 18 | } 19 | 20 | $result = $pdo->query("SELECT * FROM users LIMIT 2"); 21 | echo PHP_EOL . "Use LIMIT 2" . PHP_EOL; 22 | while ($record = $result->fetch()) { 23 | echo implode("\t", $record) . PHP_EOL; 24 | } 25 | 26 | $result = $pdo->query("SELECT * FROM users WHERE id > 3"); 27 | echo PHP_EOL . "Use WHERE id > 3" . PHP_EOL; 28 | while ($record = $result->fetch()) { 29 | echo implode("\t", $record) . PHP_EOL; 30 | } 31 | 32 | $result = $pdo->query("SELECT * FROM users ORDER BY id DESC"); 33 | echo PHP_EOL . "Use ORDER BY id DESC" . PHP_EOL; 34 | while ($record = $result->fetch()) { 35 | echo implode("\t", $record) . PHP_EOL; 36 | } 37 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.9/form-csrf.php: -------------------------------------------------------------------------------- 1 | ERROR: The CSRF Token was not found in POST payload.

'; 12 | } elseif ($_POST['csrf-token'] !== $_SESSION['csrf-token']) { 13 | echo '

ERROR: The CSRF Token is not valid.

'; 14 | } else { 15 | echo '

OK: The CSRF Token is valid. Will continue with email validation...

'; 16 | } 17 | } 18 | 19 | ?> 20 |
21 |
22 |
23 |
24 | 25 | 26 | 28 |
29 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/components/Auth.php: -------------------------------------------------------------------------------- 1 | getUserById((int)$_SESSION['userid']); 24 | } 25 | return null; 26 | } 27 | 28 | public static function authenticate(int $id) 29 | { 30 | $_SESSION['userid'] = $id; 31 | $_SESSION['loginTime'] = time(); 32 | } 33 | 34 | public static function logout() 35 | { 36 | if (session_status() === PHP_SESSION_ACTIVE) { 37 | $_SESSION = []; // clear the stored values in current call $_SESSION 38 | session_regenerate_id(true); 39 | session_destroy(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/tests/Tests/RouterTest.php: -------------------------------------------------------------------------------- 1 | assertNull($router->getHandler()); 20 | 21 | $_SERVER['PATH_INFO'] = '/profile'; 22 | $this->assertInstanceOf(Profile::class, $router->getHandler()); 23 | 24 | $_SERVER['PATH_INFO'] = '/login'; 25 | $this->assertInstanceOf(Login::class, $router->getHandler()); 26 | 27 | $_SERVER['PATH_INFO'] = '/logout'; 28 | $this->assertInstanceOf(Logout::class, $router->getHandler()); 29 | 30 | $_SERVER['PATH_INFO'] = '/unknown'; 31 | $handler = $router->getHandler(); 32 | $this->assertIsObject($handler); 33 | $this->assertInstanceOf(Handler::class, $handler); 34 | 35 | unset($_SERVER['PATH_INFO']); 36 | $this->assertNull($router->getHandler()); 37 | } 38 | } -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/tests/Tests/RouterTest.php: -------------------------------------------------------------------------------- 1 | assertNull($router->getHandler()); 20 | 21 | $_SERVER['PATH_INFO'] = '/profile'; 22 | $this->assertInstanceOf(Profile::class, $router->getHandler()); 23 | 24 | $_SERVER['PATH_INFO'] = '/login'; 25 | $this->assertInstanceOf(Login::class, $router->getHandler()); 26 | 27 | $_SERVER['PATH_INFO'] = '/logout'; 28 | $this->assertInstanceOf(Logout::class, $router->getHandler()); 29 | 30 | $_SERVER['PATH_INFO'] = '/unknown'; 31 | $handler = $router->getHandler(); 32 | $this->assertIsObject($handler); 33 | $this->assertInstanceOf(Handler::class, $handler); 34 | 35 | unset($_SERVER['PATH_INFO']); 36 | $this->assertNull($router->getHandler()); 37 | } 38 | } -------------------------------------------------------------------------------- /Chapter10/Exercise10.4/spamcheck.php: -------------------------------------------------------------------------------- 1 | 'https://spamcheck.postmarkapp.com/']); 10 | 11 | $requestBody = json_encode([ 12 | 'email' => $email, 13 | 'options' => 'short' 14 | ]); 15 | 16 | try 17 | { 18 | $response = $client->request('POST', '/filter', [ 19 | 'headers' => [ 20 | 'Accept' => 'application/json', 21 | 'Content-Type' => 'application/json' 22 | ], 23 | 'body' => $requestBody 24 | ]); 25 | 26 | if ($response->getStatusCode() !== 200) { 27 | throw new Exception("Status code was {$response->getStatusCode()}, not 200"); 28 | } 29 | 30 | $responseObject = json_decode($response->getBody()->getContents()); 31 | 32 | if ($responseObject->success !== true) { 33 | throw new Exception("Service returned an unsuccessful response: {$responseObject->message}"); 34 | } 35 | 36 | echo "The SpamAssassin score for email {$email} is {$responseObject->score}" . PHP_EOL; 37 | } 38 | catch (Exception $ex) 39 | { 40 | echo "An error occurred: " . $ex->getMessage() . PHP_EOL; 41 | } -------------------------------------------------------------------------------- /Chapter06/Exercise6.3/session.php: -------------------------------------------------------------------------------- 1 | The cookie with session name [%s] and value [%s] ' . 12 | 'is set in browser, and sent to script.

', $sessionName, $_COOKIE[$sessionName]); 13 | echo sprintf('

The current session has the following data:

%s

', var_export($_SESSION, true)); 14 | } else { 15 | echo sprintf('

The cookie with session name [%s] does not exist.

', $sessionName); 16 | echo sprintf( 17 | '

A new cookie will be set for session name [%s], with value [%s]

', 18 | $sessionName, 19 | session_id() 20 | ); 21 | $names = [ 22 | "A-Bomb (HAS)", 23 | "Captain America", 24 | "Black Panther", 25 | ]; 26 | $chosen = $names[rand(0, 2)]; 27 | 28 | $_SESSION['name'] = $chosen; 29 | echo sprintf('

The name [%s] was picked and stored in current session.

', $chosen); 30 | echo sprintf('List of headers to send in response:
%s
', implode("\n", headers_list())); 31 | } 32 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/models/User.php: -------------------------------------------------------------------------------- 1 | id = (int)($input['id'] ?? 0); 24 | $this->username = (string)($input['username'] ?? ''); 25 | $this->password = (string)($input['password'] ?? ''); 26 | $this->signupTime = new DateTime($input['signup_time'] ?? 'now', new \DateTimeZone('UTC')); 27 | } 28 | 29 | public function getId(): int 30 | { 31 | return $this->id; 32 | } 33 | 34 | public function getUsername(): string 35 | { 36 | return $this->username; 37 | } 38 | 39 | public function getSignupTime(): DateTime 40 | { 41 | return $this->signupTime; 42 | } 43 | 44 | public function passwordMatches(string $formPassword): bool 45 | { 46 | return password_verify($formPassword, $this->password); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.10/date.php: -------------------------------------------------------------------------------- 1 | getMessage(), PHP_EOL; 38 | exit(1); 39 | } 40 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.5/Car.php: -------------------------------------------------------------------------------- 1 | getMake() . PHP_EOL; 18 | echo " Model: " . $car->getModel() . PHP_EOL; 19 | echo " Color: " . $car->getColor() . PHP_EOL; 20 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 21 | 22 | echo " No of Doors: " . $car->doors . PHP_EOL; 23 | echo " Transmission: " . $car->transmission . PHP_EOL; 24 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 25 | */ 26 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 27 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 28 | 29 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 30 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 31 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 32 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 33 | 34 | echo "Available cars are " . Car::$counter . PHP_EOL; -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/tests/Tests/HandlerTest.php: -------------------------------------------------------------------------------- 1 | assertFalse($handler->willRedirect()); 26 | $handler->requestRedirect('/some-uri'); 27 | $this->assertTrue($handler->willRedirect()); 28 | $this->assertSame('abc', $handler->handle()); 29 | } 30 | 31 | /** 32 | * @runInSeparateProcess 33 | */ 34 | public function testLogout() 35 | { 36 | $handler = new Logout(); 37 | $handler->handle(); 38 | $this->assertTrue($handler->willRedirect()); 39 | } 40 | 41 | public function testProfileHandler() 42 | { 43 | $handler = new Profile(); 44 | $this->assertSame('Profile - Learning PHP', $handler->getTitle()); 45 | } 46 | } -------------------------------------------------------------------------------- /Chapter07/Activity7.1/web/index.php: -------------------------------------------------------------------------------- 1 | 'My main template', 25 | ]; 26 | 27 | $router = new Router(); 28 | if ($handler = $router->getHandler()) { 29 | $content = $handler->handle(); 30 | if ($handler->willRedirect()) { 31 | return; 32 | } 33 | $templateData['content'] = $content; 34 | $templateData['title'] = $handler->getTitle(); 35 | } 36 | 37 | echo $mainTemplate->render($templateData); 38 | -------------------------------------------------------------------------------- /Chapter08/Activity8.1/tests/Tests/FactorialTest.php: -------------------------------------------------------------------------------- 1 | assertSame(2, calculateFactorial(2)); 18 | } 19 | 20 | public function testFactorialOfString20() 21 | { 22 | $this->assertSame(2432902008176640000, calculateFactorial('20')); 23 | } 24 | 25 | public function testFactorialOf21ThrowsTypeError() 26 | { 27 | $this->expectException(TypeError::class); 28 | calculateFactorial(21); 29 | } 30 | 31 | public function testFactorialNotANumber() 32 | { 33 | $this->expectException(NotANumber::class); 34 | calculateFactorial('a'); 35 | } 36 | 37 | public function testFactorialDecimalNumber() 38 | { 39 | $this->expectException(DecimalNumber::class); 40 | calculateFactorial(2.2); 41 | } 42 | 43 | public function testFactorialNumberIsZeroOrNegative() 44 | { 45 | $this->expectException(NumberIsZeroOrNegative::class); 46 | calculateFactorial(-3); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter08/Exercise8.6/validate-email.php: -------------------------------------------------------------------------------- 1 | context = $context; 10 | } 11 | 12 | public function getContext(): array 13 | { 14 | return $this->context; 15 | } 16 | } 17 | 18 | function validateEmail(array $input) 19 | { 20 | if (!isset($input[1])) { 21 | throw new InvalidArgumentException('No value to check.'); 22 | } 23 | $testInput = $input[1]; 24 | if (!filter_var($testInput, FILTER_VALIDATE_EMAIL)) { 25 | $error = new InvalidEmail('The email validation has failed.'); 26 | $error->setContext(['testValue' => $testInput]); 27 | throw $error; 28 | } 29 | } 30 | 31 | try { 32 | validateEmail($argv); 33 | echo 'The input value is valid email.', PHP_EOL; 34 | } catch (Throwable $e) { 35 | echo sprintf( 36 | 'Caught [%s]: %s (file: %s, line: %s, context: %s)', 37 | get_class($e), 38 | $e->getMessage(), 39 | $e->getFile(), 40 | $e->getLine(), 41 | $e instanceof InvalidEmail ? json_encode($e->getContext()) : 'N/A' 42 | ) . PHP_EOL; 43 | } 44 | -------------------------------------------------------------------------------- /Chapter03/Activity3.1/activity-movies.php: -------------------------------------------------------------------------------- 1 | ["The Terminal", "Minority Report", "Catch Me If You Can", "Lincoln", "Bridge of Spies"], 9 | 10 | "Christopher Nolan" => ["Dunkirk", "Interstellar", "The Dark Knight Rises", "Inception", "Memento"], 11 | 12 | "Martin Scorsese" => ["Silence", "Hugo", "Shutter Island", "The Departed", "Gangs of New York"], 13 | 14 | "Spike Lee" => ["Do the Right Thing", "Malcolm X", "Summer of Sam", "25th Hour", "Inside Man"], 15 | 16 | "Lynne Ramsey" => ["Ratcatcher", "Swimmer", "Morvern Callar", "We Need To Talk About Kevin", "You Were Never Really Here"] 17 | ]; 18 | 19 | $directorsCounter = 1; 20 | foreach ($directors as $director => $movies) { 21 | if ($directorsCounter > $directorsLimit) { 22 | break; 23 | } 24 | 25 | echo "$director's movies: " . PHP_EOL; 26 | 27 | $moviesCounter = 1; 28 | foreach ($movies as $movie) { 29 | if ($moviesCounter > $moviesLimit) { 30 | break; 31 | } 32 | 33 | echo " > $movie " . PHP_EOL; 34 | $moviesCounter++; 35 | } 36 | $directorsCounter++; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/handlers/Login.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/profile'); 15 | return ''; 16 | } 17 | $formError = []; 18 | if (count($_POST)) { 19 | $formUsername = $_POST['username'] ?? ''; 20 | $formPassword = $_POST['password'] ?? ''; 21 | $user = Database::instance()->getUserByUsername($formUsername); 22 | if (!$user) { 23 | $formError = ['username' => sprintf('The username [%s] was not found.', $formUsername)]; 24 | } elseif (!$user->passwordMatches($formPassword)) { 25 | $formError = ['password' => 'The provided password is invalid.']; 26 | } else { 27 | Auth::authenticate((int)$user->getId()); 28 | $this->requestRedirect('/profile'); 29 | return ''; 30 | } 31 | } 32 | 33 | return (new Template('login-form'))->render([ 34 | 'formError' => $formError, 35 | 'formUsername' => $formUsername ?? '' 36 | ]); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/Tests/UserTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(0, $user->getId()); 14 | $this->assertEquals('', $user->getUsername()); 15 | $this->assertInstanceOf(\DateTime::class, $user->getSignupTime()); 16 | } 17 | 18 | public function testUserData() 19 | { 20 | $username = 'alex'; 21 | $password = 'randomPass'; 22 | $passwordHash = password_hash($password, PASSWORD_BCRYPT); 23 | $signupTime = '2019-02-03 14:15:16'; 24 | $user = new User([ 25 | 'id' => 123, 26 | 'username' => $username, 27 | 'password' => $passwordHash, 28 | 'signup_time' => $signupTime, 29 | ]); 30 | 31 | $this->assertEquals(123, $user->getId()); 32 | $this->assertEquals($username, $user->getUsername()); 33 | $this->assertInstanceOf(\DateTime::class, $user->getSignupTime()); 34 | $this->assertEquals($signupTime, $user->getSignupTime()->format('Y-m-d H:i:s')); 35 | $this->assertTrue($user->passwordMatches($password)); 36 | $this->assertFalse($user->passwordMatches($password . 'extra')); 37 | } 38 | } -------------------------------------------------------------------------------- /Chapter06/Activity6.1/src/templates/main.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <?= ($title ?? '(no title)'); ?> 7 | 8 | 9 | 10 | 24 | 25 |
26 | 29 |
30 |

Hello, world!

31 |

This is the main layout, loaded from

32 |
33 | No content was provided for main layout. 34 |
35 |
36 | 37 |
38 | 39 | 40 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.2/Vehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 12 | $this->model = $model; 13 | $this->color = $color; 14 | $this->noOfWheels = $wheels; 15 | $this->engineNumber = $engineNo; 16 | } 17 | function getMake() 18 | { 19 | return $this->make; 20 | } 21 | function getModel() 22 | { 23 | return $this->model; 24 | } 25 | function getColor() 26 | { 27 | return $this->color; 28 | } 29 | function getNoOfWheels() 30 | { 31 | return $this->noOfWheels; 32 | } 33 | function getEngineNumber() 34 | { 35 | return $this->engineNumber; 36 | } 37 | function setMake($make) 38 | { 39 | $this->make = $make; 40 | } 41 | function setModel($model) 42 | { 43 | $this->model = $model; 44 | } 45 | function setColor($color) 46 | { 47 | $this->color = $color; 48 | } 49 | function setNoOfWheels($wheels) 50 | { 51 | $this->noOfWheels = $wheels; 52 | } 53 | function setEngineNumber($engineNo) 54 | { 55 | $this->engineNumber = $engineNo; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/templates/main.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <?php echo($title ?? '(no title)'); ?> 7 | 8 | 9 | 10 | 24 | 25 |
26 | 29 |
30 |

Hello, world!

31 |

This is the main layout, loaded from

32 |
33 | No content was provided for main layout. 34 |
35 |
36 | 37 |
38 | 39 | 40 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.10/bootstrap-homepage/src/templates/main.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <?php echo($title ?? '(no title)'); ?> 7 | 8 | 9 | 10 | 24 | 25 |
26 | 29 |
30 |

Hello, world!

31 |

This is the main layout, loaded from

32 |
33 | No content was provided for main layout. 34 |
35 |
36 | 37 |
38 | 39 | 40 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.4/super-get-href.php: -------------------------------------------------------------------------------- 1 | [ 6 | "id" => 1017100, 7 | "name" => "A-Bomb (HAS)", 8 | ], 9 | "captain-america" => [ 10 | "id" => 1009220, 11 | "name" => "Captain America", 12 | ], 13 | "black-panther" => [ 14 | "id" => 1009187, 15 | "name" => "Black Panther", 16 | ], 17 | ]; 18 | 19 | function path(array $queryData) 20 | { 21 | return sprintf('./super-get-href.php?%s', http_build_query($queryData)); 22 | } 23 | 24 | $selectedHero = []; 25 | 26 | // process the "hero" query string entry, if any 27 | if (array_key_exists('hero', $_GET)) { 28 | if (array_key_exists($_GET['hero'], $heroes)) { 29 | $heroId = $_GET['hero']; 30 | $selectedHero = $heroes[$heroId]; 31 | } 32 | } 33 | 34 | $heroLinks = []; 35 | foreach ($heroes as $heroId => $heroData) { 36 | $heroLinks[] = sprintf('%s', path(['hero' => $heroId]), $heroData['name']); 37 | } 38 | echo sprintf('

%s

', implode(' // ', $heroLinks)); // output the links 39 | ?> 40 | 41 |
42 |

Selected hero:

43 | 44 |

45 |

ID:

46 | 47 |

None.

48 | 49 |
50 |
51 |

The value of $_GET is:

52 |
53 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.3/Vehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 14 | $this->model = $model; 15 | $this->color = $color; 16 | $this->noOfWheels = $wheels; 17 | $this->engineNumber = $engineNo; 18 | } 19 | 20 | function getMake() 21 | { 22 | return $this->make; 23 | } 24 | 25 | function getModel() 26 | { 27 | return $this->model; 28 | } 29 | 30 | function getColor() 31 | { 32 | return $this->color; 33 | } 34 | 35 | function getNoOfWheels() 36 | { 37 | return $this->noOfWheels; 38 | } 39 | 40 | function getEngineNumber() 41 | { 42 | return $this->engineNumber; 43 | } 44 | 45 | function setMake($make) 46 | { 47 | $this->make = $make; 48 | } 49 | 50 | function setModel($model) 51 | { 52 | $this->model = $model; 53 | } 54 | 55 | function setColor($color) 56 | { 57 | $this->color = $color; 58 | } 59 | 60 | function setNoOfWheels($wheels) 61 | { 62 | $this->noOfWheels = $wheels; 63 | } 64 | 65 | function setEngineNumber($engineNo) 66 | { 67 | $this->engineNumber = $engineNo; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.4/Vehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 14 | $this->model = $model; 15 | $this->color = $color; 16 | $this->noOfWheels = $wheels; 17 | $this->engineNumber = $engineNo; 18 | } 19 | 20 | function getMake() 21 | { 22 | return $this->make; 23 | } 24 | 25 | function getModel() 26 | { 27 | return $this->model; 28 | } 29 | 30 | function getColor() 31 | { 32 | return $this->color; 33 | } 34 | 35 | function getNoOfWheels() 36 | { 37 | return $this->noOfWheels; 38 | } 39 | 40 | function getEngineNumber() 41 | { 42 | return $this->engineNumber; 43 | } 44 | 45 | function setMake($make) 46 | { 47 | $this->make = $make; 48 | } 49 | 50 | function setModel($model) 51 | { 52 | $this->model = $model; 53 | } 54 | 55 | function setColor($color) 56 | { 57 | $this->color = $color; 58 | } 59 | 60 | function setNoOfWheels($wheels) 61 | { 62 | $this->noOfWheels = $wheels; 63 | } 64 | 65 | function setEngineNumber($engineNo) 66 | { 67 | $this->engineNumber = $engineNo; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.6/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 17 | $this->engineStatus = true; 18 | } 19 | } 20 | } 21 | 22 | /* 23 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 24 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 25 | echo " Make: " . $motorcycle->make . PHP_EOL; 26 | echo " Model: " . $motorcycle->model . PHP_EOL; 27 | echo " Color: " . $motorcycle->color . PHP_EOL; 28 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 29 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 30 | */ 31 | 32 | /* 33 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 34 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 35 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 36 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 37 | */ 38 | 39 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 40 | 41 | $motorcycle->start(); 42 | echo "The motorcycle is " . ($motorcycle->getEngineStatus()?'running':'stopped') . PHP_EOL; 43 | $motorcycle->stop(); 44 | echo "The motorcycle is " . ($motorcycle->getEngineStatus()?'running':'stopped') . PHP_EOL; 45 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/components/Router.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/profile'); 34 | } 35 | return (new Template('home'))->render(); 36 | } 37 | }; 38 | default: 39 | return new class extends Handler 40 | { 41 | public function handle(): string 42 | { 43 | $this->requestRedirect('/'); 44 | return ''; 45 | } 46 | }; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/templates/login-form.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Authenticate

5 |

Use admin for both username and password.

6 |
7 | 8 |
9 | 10 | 13 | %s
', htmlentities($formError['username'])); 15 | } ?> 16 |
17 | 18 |
19 | 20 | 22 | %s
', htmlentities($formError['password'])); 24 | } ?> 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/src/templates/login-form.php: -------------------------------------------------------------------------------- 1 | 5 |
6 |
7 |
8 |

Authenticate

9 |
10 | 11 |
12 | 13 | 16 | %s
', htmlentities($formError['username'])); 18 | } ?> 19 |
20 | 21 |
22 | 23 | 25 | %s
', htmlentities($formError['password'])); 27 | } ?> 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.5/super-post-form.php: -------------------------------------------------------------------------------- 1 | [ 6 | "id" => 1017100, 7 | "name" => "A-Bomb (HAS)", 8 | ], 9 | "captain-america" => [ 10 | "id" => 1009220, 11 | "name" => "Captain America", 12 | ], 13 | "black-panther" => [ 14 | "id" => 1009187, 15 | "name" => "Black Panther", 16 | ], 17 | ]; 18 | 19 | $selectedHero = []; 20 | 21 | // process the post request, if any 22 | if (array_key_exists('hero', $_POST)) { 23 | if (array_key_exists($_POST['hero'], $heroes)) { 24 | $heroId = $_POST['hero']; 25 | $selectedHero = $heroes[$heroId]; 26 | } 27 | } 28 | 29 | // continue with the template 30 | ?> 31 |
32 | 33 | 38 | 39 |
40 | 41 |
42 |

Selected hero:

43 | 44 |

45 |

ID:

46 | 47 |

None.

48 | 49 |
50 |
51 |

The value of $_POST is:

52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.11/bootstrap/src/handlers/Login.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 11 | return ''; 12 | } 13 | $username = 'admin'; 14 | // for convenience, generate password hash with command line 15 | // > php -r "echo password_hash('admin', PASSWORD_BCRYPT);" 16 | $passwordHash = '$2y$10$Y09UvSz2tQCw/454Mcuzzuo8ARAjzAGGf8OPGeBloO7j47Fb2v.lu'; // "admin" password hash 17 | 18 | $formError = []; 19 | if ($_SERVER['REQUEST_METHOD'] === 'POST') { 20 | $formUsername = $_POST['username'] ?? ''; 21 | $formPassword = $_POST['password'] ?? ''; 22 | if ($formUsername !== $username) { 23 | $formError = ['username' => sprintf('The username [%s] was not found.', $formUsername)]; 24 | } elseif (!password_verify($formPassword, $passwordHash)) { 25 | $formError = ['password' => 'The provided password is invalid.']; 26 | } else { 27 | $_SESSION['username'] = $username; 28 | $_SESSION['loginTime'] = date(\DATE_COOKIE); 29 | $this->requestRedirect('/profile'); 30 | return ''; 31 | } 32 | } 33 | 34 | return (new \Components\Template('login-form'))->render([ 35 | 'formError' => $formError, 36 | 'formUsername' => $formUsername ?? '' 37 | ]); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.5/Vehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 16 | $this->model = $model; 17 | $this->color = $color; 18 | $this->noOfWheels = $wheels; 19 | $this->engineNumber = $engineNo; 20 | self::$counter++; 21 | } 22 | 23 | function getMake() 24 | { 25 | return $this->make; 26 | } 27 | 28 | function getModel() 29 | { 30 | return $this->model; 31 | } 32 | 33 | function getColor() 34 | { 35 | return $this->color; 36 | } 37 | 38 | function getNoOfWheels() 39 | { 40 | return $this->noOfWheels; 41 | } 42 | 43 | function getEngineNumber() 44 | { 45 | return $this->engineNumber; 46 | } 47 | 48 | function setMake($make) 49 | { 50 | $this->make = $make; 51 | } 52 | 53 | function setModel($model) 54 | { 55 | $this->model = $model; 56 | } 57 | 58 | function setColor($color) 59 | { 60 | $this->color = $color; 61 | } 62 | 63 | function setNoOfWheels($wheels) 64 | { 65 | $this->noOfWheels = $wheels; 66 | } 67 | 68 | function setEngineNumber($engineNo) 69 | { 70 | $this->engineNumber = $engineNo; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.1/Vehicle.php: -------------------------------------------------------------------------------- 1 | make; 12 | } 13 | function getModel() 14 | { 15 | return $this->model; 16 | } 17 | function getColor() 18 | { 19 | return $this->color; 20 | } 21 | function getNoOfWheels() 22 | { 23 | return $this->noOfWheels; 24 | } 25 | function getEngineNumber() 26 | { 27 | return $this->engineNumber; 28 | } 29 | function setMake($make) 30 | { 31 | $this->make = $make; 32 | } 33 | function setModel($model) 34 | { 35 | $this->model = $model; 36 | } 37 | function setColor($color) 38 | { 39 | $this->color = $color; 40 | } 41 | function setNoOfWheels($wheels) 42 | { 43 | $this->noOfWheels = $wheels; 44 | } 45 | function setEngineNumber($engineNo) 46 | { 47 | $this->engineNumber = $engineNo; 48 | } 49 | } 50 | $object = new Vehicle(); 51 | $object->setMake('Honda'); 52 | $object->setModel('Civic'); 53 | $object->setColor('Red'); 54 | $object->setNoOfWheels(4); 55 | $object->setEngineNumber('ABC123456'); 56 | echo "Make : " . $object->getMake() . PHP_EOL; 57 | echo "Model : " . $object->getModel() . PHP_EOL; 58 | echo "Color : " . $object->getColor() . PHP_EOL; 59 | echo "No. of wheels : " . $object->getNoOfWheels() . PHP_EOL; 60 | echo "Engine no. : " . $object->getEngineNumber() . PHP_EOL; 61 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/templates/main.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | <?= ($title ?? '(no title)'); ?> 8 | 9 | 10 | 11 | 36 | 37 |
38 | render(); 42 | } ?> 43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.6/Car.php: -------------------------------------------------------------------------------- 1 | hasKeyinIgnition) { 17 | $this->engineStatus = true; 18 | } 19 | } 20 | } 21 | /* 22 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 23 | echo "Vehicle Type: " . get_class($car) . PHP_EOL; 24 | echo " Make: " . $car->getMake() . PHP_EOL; 25 | echo " Model: " . $car->getModel() . PHP_EOL; 26 | echo " Color: " . $car->getColor() . PHP_EOL; 27 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 28 | 29 | echo " No of Doors: " . $car->doors . PHP_EOL; 30 | echo " Transmission: " . $car->transmission . PHP_EOL; 31 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 32 | */ 33 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 34 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 35 | /* 36 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 37 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 38 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 39 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 40 | 41 | echo "Available cars are " . Car::$counter . PHP_EOL; 42 | */ 43 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 44 | 45 | $car->start(); 46 | echo "The car is " . ($car->getEngineStatus()?'running':'stopped') . PHP_EOL; 47 | $car->stop(); 48 | echo "The car is " . ($car->getEngineStatus()?'running':'stopped') . PHP_EOL; 49 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/templates/login-form.php: -------------------------------------------------------------------------------- 1 | 5 |
6 |
7 |
8 |

Authenticate

9 |
10 | 11 |
12 | 13 | 16 | %s
', htmlentities($formError['username'])); 18 | } ?> 19 |
20 | 21 |
22 | 23 | 25 | %s
', htmlentities($formError['password'])); 27 | } ?> 28 | 29 | 30 | 31 | 32 |
33 |

No account? Sign up here.

34 |
35 | 36 | 37 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.6/super-post-upload.php: -------------------------------------------------------------------------------- 1 | my uploaded image', $relativeFilename); 35 | } 36 | 37 | ?> 38 | 39 |
40 | 41 | 42 |
43 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.6/AbstractVehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 14 | $this->model = $model; 15 | $this->color = $color; 16 | $this->noOfWheels = $wheels; 17 | $this->engineNumber = $engineNo; 18 | self::$counter++; 19 | } 20 | function getMake() 21 | { 22 | return $this->make; 23 | } 24 | function getModel() 25 | { 26 | return $this->model; 27 | } 28 | function getColor() 29 | { 30 | return $this->color; 31 | } 32 | function getNoOfWheels() 33 | { 34 | return $this->noOfWheels; 35 | } 36 | function getEngineNumber() 37 | { 38 | return $this->engineNumber; 39 | } 40 | function setMake($make) 41 | { 42 | $this->make = $make; 43 | } 44 | function setModel($model) 45 | { 46 | $this->model = $model; 47 | } 48 | function setColor($color) 49 | { 50 | $this->color = $color; 51 | } 52 | function setNoOfWheels($wheels) 53 | { 54 | $this->noOfWheels = $wheels; 55 | } 56 | function setEngineNumber($engineNo) 57 | { 58 | $this->engineNumber = $engineNo; 59 | } 60 | abstract function start(); 61 | function stop() 62 | { 63 | $this->engineStatus = false; 64 | } 65 | function getEngineStatus() 66 | { 67 | return $this->engineStatus; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Chapter06/Exercise6.7/input-sanitize.php: -------------------------------------------------------------------------------- 1 | Stars input is not set.

'; 10 | } elseif (false === $stars) { 11 | // treat the case when the filter fails 12 | echo '

Stars failed to pass the sanitization filter.

'; 13 | } else { 14 | // first approach 15 | $stars = (int)$stars; 16 | if($stars < 1 || $stars > 5){ 17 | echo '

Stars can have values between 1 and 5.

'; 18 | } 19 | // or second approach 20 | $stars = filter_var($stars, FILTER_VALIDATE_INT, [ 21 | 'options' => [ 22 | 'default' => 0, // value to return if the filter fails 23 | 'min_range' => 1, 24 | 'max_range' => 5, 25 | ] 26 | ]); 27 | if(0 === $stars){ 28 | echo '

Stars can have values between 1 and 5.

'; 29 | } 30 | } 31 | 32 | if (null === $message) { 33 | // treat the case when input does not exist 34 | echo '

Message input is not set.

'; 35 | } elseif (false === $message) { 36 | // treat the case when the filter fails 37 | echo '

Message failed to pass the sanitization filter.

'; 38 | } 39 | 40 | echo sprintf("

Stars: %s

Message: %s

", var_export($stars, true), var_export($message, true)); 41 | 42 | ?> 43 | 44 |
45 | 46 |
47 |
48 |
49 |
50 |
51 | 52 |
53 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.7/AbstractVehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 16 | $this->model = $model; 17 | $this->color = $color; 18 | $this->noOfWheels = $wheels; 19 | $this->engineNumber = $engineNo; 20 | self::$counter++; 21 | } 22 | 23 | function getMake() 24 | { 25 | return $this->make; 26 | } 27 | 28 | function getModel() 29 | { 30 | return $this->model; 31 | } 32 | 33 | function getColor() 34 | { 35 | return $this->color; 36 | } 37 | 38 | function getNoOfWheels() 39 | { 40 | return $this->noOfWheels; 41 | } 42 | 43 | function getEngineNumber() 44 | { 45 | return $this->engineNumber; 46 | } 47 | 48 | function setMake($make) 49 | { 50 | $this->make = $make; 51 | } 52 | 53 | function setModel($model) 54 | { 55 | $this->model = $model; 56 | } 57 | 58 | function setColor($color) 59 | { 60 | $this->color = $color; 61 | } 62 | 63 | function setNoOfWheels($wheels) 64 | { 65 | $this->noOfWheels = $wheels; 66 | } 67 | 68 | function setEngineNumber($engineNo) 69 | { 70 | $this->engineNumber = $engineNo; 71 | } 72 | 73 | abstract function start(); 74 | 75 | function stop() 76 | { 77 | $this->engineStatus = false; 78 | } 79 | 80 | function getEngineStatus() 81 | { 82 | return $this->engineStatus; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/src/handlers/Login.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/'); 12 | return ''; 13 | } 14 | $formError = []; 15 | if ($_SERVER['REQUEST_METHOD'] === 'POST') { 16 | $formUsername = $_POST['username'] ?? ''; 17 | $formPassword = $_POST['password'] ?? ''; 18 | $userData = $this->getUserData($formUsername); 19 | if (!$userData) { 20 | $formError = ['username' => sprintf('The username [%s] was not found.', $formUsername)]; 21 | } elseif (!password_verify($formPassword, $userData['password'])) { 22 | $formError = ['password' => 'The provided password is invalid.']; 23 | } else { 24 | $_SESSION['username'] = $formUsername; 25 | $_SESSION['userdata'] = $userData; 26 | $this->requestRedirect('/profile'); 27 | return ''; 28 | } 29 | } 30 | 31 | return (new \Components\Template('login-form'))->render([ 32 | 'formError' => $formError, 33 | 'formUsername' => $formUsername ?? '' 34 | ]); 35 | } 36 | 37 | private function getUserData(string $username): ?array 38 | { 39 | $users = [ 40 | 'vip' => [ 41 | 'level' => 'VIP', 42 | 'password' => '$2y$10$JmCj4KVnBizmy6WS3I/bXuYM/yEI3dRg/IYkGdqHrBlOu4FKOliMa', // "vip" password hash 43 | ], 44 | 'user' => [ 45 | 'level' => 'STANDARD', 46 | 'password' => '$2y$10$QONapyews4J75ijOsPcjH.iJ4bHd09hf1bD5b0BsDNMKkK/fn130y', // "user" password hash 47 | ], 48 | ]; 49 | return $users[$username] ?? null; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/Tests/RouterTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(Profile::class, $router->getHandler()); 25 | 26 | $_SERVER['PATH_INFO'] = '/login'; 27 | $this->assertInstanceOf(Login::class, $router->getHandler()); 28 | 29 | $_SERVER['PATH_INFO'] = '/logout'; 30 | $this->assertInstanceOf(Logout::class, $router->getHandler()); 31 | 32 | $_SERVER['PATH_INFO'] = '/signup'; 33 | $this->assertInstanceOf(Signup::class, $router->getHandler()); 34 | 35 | $_SERVER['PATH_INFO'] = '/contacts'; 36 | $this->assertInstanceOf(Contacts::class, $router->getHandler()); 37 | 38 | $_SERVER['PATH_INFO'] = '/unknown'; 39 | $handler = $router->getHandler(); 40 | $handler->handle(); 41 | $this->assertIsObject($handler); 42 | $this->assertInstanceOf(Handler::class, $handler); 43 | $this->assertTrue($handler->willRedirect()); 44 | 45 | $_SERVER['PATH_INFO'] = '/'; 46 | $handlerSlash = $router->getHandler(); 47 | $this->assertIsObject($handlerSlash); 48 | $this->assertInstanceOf(Handler::class, $handlerSlash); 49 | 50 | unset($_SERVER['PATH_INFO']); 51 | $handlerDefault = $router->getHandler(); 52 | $this->assertIsObject($handlerSlash); 53 | $this->assertInstanceOf(Handler::class, $handlerSlash); 54 | $this->assertEquals($handlerSlash, $handlerDefault); 55 | } 56 | } -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/Tests/HandlerTest.php: -------------------------------------------------------------------------------- 1 | assertSame('abc', $handler->handle()); 23 | } 24 | 25 | /** 26 | * @runInSeparateProcess 27 | */ 28 | public function testHandlerRedirect() 29 | { 30 | $handler = new class extends Handler 31 | { 32 | public function handle(): string 33 | { 34 | return ''; 35 | } 36 | }; 37 | 38 | $this->assertFalse($handler->willRedirect()); 39 | $handler->requestRedirect('/some-uri'); 40 | $this->assertTrue($handler->willRedirect()); 41 | } 42 | 43 | /** 44 | * @runInSeparateProcess 45 | */ 46 | public function testHandlerRefresh() 47 | { 48 | $handler = new class extends Handler 49 | { 50 | public function handle(): string 51 | { 52 | return ''; 53 | } 54 | }; 55 | 56 | // test refresh 57 | $_SERVER['REQUEST_URI'] = '/'; 58 | $this->assertFalse($handler->willRedirect()); 59 | $handler->requestRefresh(); 60 | $this->assertTrue($handler->willRedirect()); 61 | } 62 | 63 | /** 64 | * @runInSeparateProcess 65 | */ 66 | public function testLogout() 67 | { 68 | $handler = new Logout(); 69 | $handler->handle(); 70 | $this->assertTrue($handler->willRedirect()); 71 | } 72 | 73 | /** 74 | * @runInSeparateProcess 75 | */ 76 | public function testProfileHandler() 77 | { 78 | $handler = new Profile(); 79 | $this->assertSame('Profile - Contacts list', $handler->getTitle()); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/tests/Tests/AuthTest.php: -------------------------------------------------------------------------------- 1 | assertFalse(Auth::userIsAuthenticated()); 13 | $_SESSION['userid'] = 12345; 14 | $this->assertTrue(Auth::userIsAuthenticated()); 15 | $_SESSION['userid'] = -1; 16 | $this->assertTrue(Auth::userIsAuthenticated()); 17 | $_SESSION['userid'] = 'dummy'; 18 | $this->assertTrue(Auth::userIsAuthenticated()); 19 | $_SESSION['userid'] = false; 20 | $this->assertTrue(Auth::userIsAuthenticated()); 21 | $_SESSION['userid'] = null; 22 | $this->assertFalse(Auth::userIsAuthenticated()); 23 | unset($_SESSION['userid']); 24 | $this->assertFalse(Auth::userIsAuthenticated()); 25 | } 26 | 27 | public function testGetLastLogin() 28 | { 29 | $_SESSION['loginTime'] = $timestamp = time(); 30 | $this->assertEquals(date(DATE_ISO8601, $timestamp), Auth::getLastLogin()->format(DATE_ISO8601)); 31 | unset($_SESSION['loginTime']); 32 | $this->expectException(\TypeError::class); 33 | Auth::getLastLogin(); 34 | } 35 | 36 | public function testAuthenticate() 37 | { 38 | Auth::authenticate(123); 39 | $this->assertTrue(Auth::userIsAuthenticated()); 40 | $this->assertInstanceOf(\DateTime::class, Auth::getLastLogin()); 41 | } 42 | 43 | /** 44 | * @runInSeparateProcess 45 | */ 46 | public function testLogout() 47 | { 48 | session_start(); 49 | $this->assertTrue(session_status() === PHP_SESSION_ACTIVE); 50 | $sessionId = session_id(); 51 | Auth::authenticate(123); 52 | $this->assertTrue(Auth::userIsAuthenticated()); 53 | $this->assertInstanceOf(\DateTime::class, Auth::getLastLogin()); 54 | Auth::logout(); 55 | $this->assertNotEquals(session_id(), $sessionId); 56 | $this->assertFalse(Auth::userIsAuthenticated()); 57 | } 58 | } -------------------------------------------------------------------------------- /Chapter05/Exercise5.8/AbstractVehicle.php: -------------------------------------------------------------------------------- 1 | make = $make; 17 | $this->model = $model; 18 | $this->color = $color; 19 | $this->noOfWheels = $wheels; 20 | $this->engineNumber = $engineNo; 21 | self::$counter++; 22 | } 23 | 24 | function getMake() 25 | { 26 | return $this->make; 27 | } 28 | 29 | function getModel() 30 | { 31 | return $this->model; 32 | } 33 | 34 | function getColor() 35 | { 36 | return $this->color; 37 | } 38 | 39 | function getNoOfWheels() 40 | { 41 | return $this->noOfWheels; 42 | } 43 | 44 | function getEngineNumber() 45 | { 46 | return $this->engineNumber; 47 | } 48 | 49 | function setMake($make) 50 | { 51 | $this->make = $make; 52 | } 53 | 54 | function setModel($model) 55 | { 56 | $this->model = $model; 57 | } 58 | 59 | function setColor($color) 60 | { 61 | $this->color = $color; 62 | } 63 | 64 | function setNoOfWheels($wheels) 65 | { 66 | $this->noOfWheels = $wheels; 67 | } 68 | 69 | function setEngineNumber($engineNo) 70 | { 71 | $this->engineNumber = $engineNo; 72 | } 73 | 74 | abstract function start(); 75 | 76 | function stop() 77 | { 78 | $this->engineStatus = false; 79 | } 80 | 81 | function getEngineStatus() 82 | { 83 | return $this->engineStatus; 84 | } 85 | 86 | function getPrice() 87 | { 88 | return $this->price; 89 | } 90 | 91 | function setPrice($price) 92 | { 93 | $this->price = $price; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/handlers/Signup.php: -------------------------------------------------------------------------------- 1 | requestRedirect('/profile'); 15 | return ''; 16 | } 17 | $formError = []; 18 | if ($_SERVER['REQUEST_METHOD'] === 'POST') { 19 | $formError = $this->handleSignup(); 20 | if (!$formError) { 21 | return ''; 22 | } 23 | } 24 | 25 | return (new Template('signup-form'))->render([ 26 | 'formError' => $formError, 27 | 'formUsername' => $_POST['username'] ?? '' 28 | ]); 29 | } 30 | 31 | private function handleSignup(): ?array 32 | { 33 | $formError = null; 34 | $formUsername = trim($_POST['username'] ?? ''); 35 | $formPassword = trim($_POST['password'] ?? ''); 36 | $formPasswordVerify = $_POST['passwordVerify'] ?? ''; 37 | if (!$formUsername || strlen($formUsername) < 3) { 38 | $formError = ['username' => 'Please enter an username of at least 3 characters.']; 39 | } elseif (!ctype_alnum($formUsername)) { 40 | $formError = ['username' => 'The username should contain only numbers and letters.']; 41 | } elseif (!$formPassword) { 42 | $formError = ['password' => 'Please enter a password of at least 6 characters.']; 43 | } elseif ($formPassword !== $formPasswordVerify) { 44 | $formError = ['passwordVerify' => 'The passwords doesn\'t match.']; 45 | } else { 46 | $stmt = Database::instance()->addUser(strtolower($formUsername), $formPassword); 47 | if (!$stmt->rowCount()) { 48 | list(, , $error) = $stmt->errorInfo(); 49 | $formError = ['username' => $error]; 50 | } else { 51 | Auth::authenticate((int)Database::instance()->pdo->lastInsertId()); 52 | $this->requestRedirect('/profile'); 53 | } 54 | } 55 | return $formError; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.7/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The motorcycle has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Gear shifted to " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "The break applied. " . PHP_EOL; 35 | } 36 | } 37 | 38 | /* 39 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 40 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 41 | echo " Make: " . $motorcycle->make . PHP_EOL; 42 | echo " Model: " . $motorcycle->model . PHP_EOL; 43 | echo " Color: " . $motorcycle->color . PHP_EOL; 44 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 45 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 46 | */ 47 | 48 | /* 49 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 50 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 51 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 52 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 53 | */ 54 | 55 | /* 56 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 57 | 58 | $motorcycle->start(); 59 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 60 | $motorcycle->stop(); 61 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 62 | */ 63 | 64 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 65 | 66 | $motorcycle->changeSpeed(45); 67 | $motorcycle->changeGear(3); 68 | $motorcycle->applyBreak(); 69 | -------------------------------------------------------------------------------- /Chapter07/Activity7.1/src/templates/signup-form.php: -------------------------------------------------------------------------------- 1 | 5 |
6 |
7 |
8 |

Sign up

9 |
10 | 11 |
12 | 13 | 16 | %s
', htmlentities($formError['username'])); 18 | } ?> 19 |
20 | 21 |
22 | 23 | 25 | %s
', htmlentities($formError['password'])); 27 | } ?> 28 | 29 | 30 |
31 | 32 | 34 | %s
', htmlentities($formError['passwordVerify'])); 36 | } ?> 37 | 38 | 39 | 40 | 41 |
42 |

Already have an account? Login here.

43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter04/Activity4.1/activity.php: -------------------------------------------------------------------------------- 1 | 2) { 17 | $number--; 18 | $factorial *= $number; 19 | } 20 | return $factorial; 21 | } 22 | 23 | /** 24 | * Return the sum of its inputs. Give as many inputs as you like. 25 | * 26 | * @return float 27 | */ 28 | function sum(): float 29 | { 30 | return array_sum(func_get_args()); 31 | } 32 | 33 | /** 34 | * Determines if the input $number is a prime number. 35 | * 36 | * It only divides the number by 2 up until the square root of the number; 37 | * 38 | * @param int $number 39 | * @return bool 40 | */ 41 | function prime(int $number): bool 42 | { 43 | // everything equal or smaller than 2 is not a prime number 44 | if (2 >= $number) { 45 | return false; 46 | } 47 | for ($i = 2; $i <= sqrt($number); $i++) { 48 | if ($number % $i === 0) { 49 | return false; 50 | } 51 | } 52 | return true; 53 | } 54 | 55 | /** 56 | * @param string $operation 57 | * @return bool|float|mixed 58 | */ 59 | function performOperation(string $operation) 60 | { 61 | switch ($operation) { 62 | case 'factorial': 63 | // get the second parameter, it must be an int. 64 | // we will cast it to int to be sure 65 | $number = (int) func_get_arg(1); 66 | return factorial($number); 67 | case 'sum': 68 | // get all parameters 69 | $params = func_get_args(); 70 | // remove the first parameter, because it is the operation 71 | array_shift($params); 72 | return call_user_func_array('sum', $params); 73 | case 'prime': 74 | $number = (int) func_get_arg(1); 75 | return prime($number); 76 | } 77 | } 78 | 79 | echo performOperation("factorial", 3) . PHP_EOL; 80 | echo performOperation('sum', 2, 2, 2) . PHP_EOL; 81 | echo (performOperation('prime', 3)) ? "The number you entered was prime.". PHP_EOL : "The number you entered was not prime." . PHP_EOL; 82 | -------------------------------------------------------------------------------- /Chapter06/Activity6.1/tests/Tests/HandlerTest.php: -------------------------------------------------------------------------------- 1 | assertFalse($handler->willRedirect()); 27 | $handler->requestRedirect('/some-uri'); 28 | $this->assertTrue($handler->willRedirect()); 29 | $this->assertSame('abc', $handler->handle()); 30 | } 31 | 32 | /** 33 | * @runInSeparateProcess 34 | */ 35 | public function testLogout() 36 | { 37 | $handler = new Logout(); 38 | $handler->handle(); 39 | $this->assertTrue($handler->willRedirect()); 40 | } 41 | 42 | /** 43 | * @runInSeparateProcess 44 | */ 45 | public function testProfileHandler() 46 | { 47 | $handler = new Profile(); 48 | $this->assertSame('Profile - Learning PHP', $handler->getTitle()); 49 | 50 | // test sent form today 51 | $hasSentFormToday = \Closure::bind(function (array $data) use ($handler) { 52 | return $handler->hasSentFormToday($data); 53 | }, $handler, $handler); 54 | $this->assertTrue($hasSentFormToday([['dateAdded' => date('Y-m-d')]])); 55 | $this->assertFalse($hasSentFormToday([['dateAdded' => date('Y-m-d', time() - 24 * 60 * 60)]])); 56 | 57 | // test refresh 58 | $_SERVER['REQUEST_URI'] = '/'; 59 | $requestRefresh = function () use ($handler) { 60 | $handler->requestRefresh(); 61 | }; 62 | $requestRefresh->call($handler); 63 | $this->assertTrue($handler->willRedirect()); 64 | } 65 | 66 | public function testLoginHandler() 67 | { 68 | $handler = new Login(); 69 | $getUserData = function (string $username) use ($handler) { 70 | return $handler->getUserData($username); 71 | }; 72 | $vipUser = $getUserData->call($handler, 'vip'); 73 | $this->assertSame('VIP', $vipUser['level'] ?? null); 74 | } 75 | } -------------------------------------------------------------------------------- /Chapter05/Exercise5.7/Car.php: -------------------------------------------------------------------------------- 1 | hasKeyinIgnition) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The car has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Shifted to gear number " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "All the 4 breaks in the wheels applied. " . PHP_EOL; 35 | } 36 | } 37 | /* 38 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 39 | echo "Vehicle Type: " . get_class($car) . PHP_EOL; 40 | echo " Make: " . $car->getMake() . PHP_EOL; 41 | echo " Model: " . $car->getModel() . PHP_EOL; 42 | echo " Color: " . $car->getColor() . PHP_EOL; 43 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 44 | 45 | echo " No of Doors: " . $car->doors . PHP_EOL; 46 | echo " Transmission: " . $car->transmission . PHP_EOL; 47 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 48 | */ 49 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 50 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 51 | /* 52 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 53 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 54 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 55 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 56 | 57 | echo "Available cars are " . Car::$counter . PHP_EOL; 58 | */ 59 | /* 60 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 61 | 62 | $car->start(); 63 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 64 | $car->stop(); 65 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 66 | */ 67 | 68 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 69 | 70 | $car->changeSpeed(65); 71 | $car->applyBreak(); 72 | $car->changeGear(4); 73 | $car->changeSpeed(75); 74 | $car->applyBreak(); 75 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.8/Car.php: -------------------------------------------------------------------------------- 1 | hasKeyinIgnition) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The car has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Shifted to gear number " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "All the 4 breaks in the wheels applied. " . PHP_EOL; 35 | } 36 | } 37 | /* 38 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 39 | echo "Vehicle Type: " . get_class($car) . PHP_EOL; 40 | echo " Make: " . $car->getMake() . PHP_EOL; 41 | echo " Model: " . $car->getModel() . PHP_EOL; 42 | echo " Color: " . $car->getColor() . PHP_EOL; 43 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 44 | 45 | echo " No of Doors: " . $car->doors . PHP_EOL; 46 | echo " Transmission: " . $car->transmission . PHP_EOL; 47 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 48 | */ 49 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 50 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 51 | /* 52 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 53 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 54 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 55 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 56 | 57 | echo "Available cars are " . Car::$counter . PHP_EOL; 58 | */ 59 | /* 60 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 61 | 62 | $car->start(); 63 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 64 | $car->stop(); 65 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 66 | */ 67 | /* 68 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 69 | 70 | $car->changeSpeed(65); 71 | $car->applyBreak(); 72 | $car->changeGear(4); 73 | $car->changeSpeed(75); 74 | $car->applyBreak(); 75 | */ -------------------------------------------------------------------------------- /Chapter05/Exercise5.8/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The motorcycle has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Gear shifted to " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "The break applied. " . PHP_EOL; 35 | } 36 | 37 | function getPrice() 38 | { 39 | return $this->price - $this->price * 0.05; 40 | } 41 | } 42 | 43 | /* 44 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 45 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 46 | echo " Make: " . $motorcycle->make . PHP_EOL; 47 | echo " Model: " . $motorcycle->model . PHP_EOL; 48 | echo " Color: " . $motorcycle->color . PHP_EOL; 49 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 50 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 51 | */ 52 | 53 | /* 54 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 55 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 56 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 57 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 58 | */ 59 | 60 | /* 61 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 62 | 63 | $motorcycle->start(); 64 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 65 | $motorcycle->stop(); 66 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 67 | */ 68 | 69 | /* 70 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 71 | 72 | $motorcycle->changeSpeed(45); 73 | $motorcycle->changeGear(3); 74 | $motorcycle->applyBreak(); 75 | */ 76 | 77 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 78 | $motorcycle->setPrice(5000); 79 | echo "The price is ". $motorcycle->getPrice() . PHP_EOL; 80 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.10/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The motorcycle has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Gear shifted to " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "The break applied. " . PHP_EOL; 35 | } 36 | 37 | function getPrice() 38 | { 39 | return $this->price - $this->price * 0.05; 40 | } 41 | } 42 | 43 | /* 44 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 45 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 46 | echo " Make: " . $motorcycle->make . PHP_EOL; 47 | echo " Model: " . $motorcycle->model . PHP_EOL; 48 | echo " Color: " . $motorcycle->color . PHP_EOL; 49 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 50 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 51 | */ 52 | 53 | /* 54 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 55 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 56 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 57 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 58 | */ 59 | 60 | /* 61 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 62 | 63 | $motorcycle->start(); 64 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 65 | $motorcycle->stop(); 66 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 67 | */ 68 | 69 | /* 70 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 71 | 72 | $motorcycle->changeSpeed(45); 73 | $motorcycle->changeGear(3); 74 | $motorcycle->applyBreak(); 75 | */ 76 | /* 77 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 78 | $motorcycle->setPrice(5000); 79 | echo "The price is ". $motorcycle->getPrice() . PHP_EOL; 80 | */ -------------------------------------------------------------------------------- /Chapter05/Exercise5.11/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The motorcycle has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Gear shifted to " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "The break applied. " . PHP_EOL; 35 | } 36 | 37 | function getPrice() 38 | { 39 | return $this->price - $this->price * 0.05; 40 | } 41 | } 42 | 43 | /* 44 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 45 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 46 | echo " Make: " . $motorcycle->make . PHP_EOL; 47 | echo " Model: " . $motorcycle->model . PHP_EOL; 48 | echo " Color: " . $motorcycle->color . PHP_EOL; 49 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 50 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 51 | */ 52 | 53 | /* 54 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 55 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 56 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 57 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 58 | */ 59 | 60 | /* 61 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 62 | 63 | $motorcycle->start(); 64 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 65 | $motorcycle->stop(); 66 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 67 | */ 68 | 69 | /* 70 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 71 | 72 | $motorcycle->changeSpeed(45); 73 | $motorcycle->changeGear(3); 74 | $motorcycle->applyBreak(); 75 | */ 76 | 77 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 78 | $motorcycle->setPrice(5000); 79 | echo "The price is ". $motorcycle->getPrice() . PHP_EOL; 80 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.9/Motorcycle.php: -------------------------------------------------------------------------------- 1 | hasKey && $this->hasKicked) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The motorcycle has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Gear shifted to " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "The break applied. " . PHP_EOL; 35 | } 36 | 37 | function getPrice() 38 | { 39 | return $this->price - $this->price * 0.05; 40 | } 41 | } 42 | 43 | /* 44 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 45 | echo "Vehicle Type: " . get_class($motorcycle) . PHP_EOL; 46 | echo " Make: " . $motorcycle->make . PHP_EOL; 47 | echo " Model: " . $motorcycle->model . PHP_EOL; 48 | echo " Color: " . $motorcycle->color . PHP_EOL; 49 | echo " No of wheels: " . $motorcycle->noOfWheels . PHP_EOL; 50 | echo " No of strokes: " . $motorcycle->stroke . PHP_EOL; 51 | */ 52 | 53 | /* 54 | $motorcycle1 = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 55 | $motorcycle2 = new Motorcycle('Suzuki', 'Gixxer SF', 'Blue', 2, '53WVC14599'); 56 | $motorcycle2 = new Motorcycle('Harley Davidson', 'Street 750', 'Black', 2, '53WVC14234'); 57 | echo "Available motorcycles are " . Motorcycle::$counter . PHP_EOL; 58 | */ 59 | 60 | /* 61 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 62 | 63 | $motorcycle->start(); 64 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 65 | $motorcycle->stop(); 66 | echo "The motorcycle is " . ($motorcycle->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 67 | */ 68 | 69 | /* 70 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 71 | 72 | $motorcycle->changeSpeed(45); 73 | $motorcycle->changeGear(3); 74 | $motorcycle->applyBreak(); 75 | */ 76 | /* 77 | $motorcycle = new Motorcycle('Kawasaki', 'Ninja', 'Orange', 2, '53WVC14598'); 78 | $motorcycle->setPrice(5000); 79 | echo "The price is ". $motorcycle->getPrice() . PHP_EOL; 80 | */ -------------------------------------------------------------------------------- /Chapter05/Exercise5.9/Car.php: -------------------------------------------------------------------------------- 1 | hasKeyinIgnition) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The car has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Shifted to gear number " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "All the 4 breaks in the wheels applied. " . PHP_EOL; 35 | } 36 | } 37 | /* 38 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 39 | echo "Vehicle Type: " . get_class($car) . PHP_EOL; 40 | echo " Make: " . $car->getMake() . PHP_EOL; 41 | echo " Model: " . $car->getModel() . PHP_EOL; 42 | echo " Color: " . $car->getColor() . PHP_EOL; 43 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 44 | 45 | echo " No of Doors: " . $car->doors . PHP_EOL; 46 | echo " Transmission: " . $car->transmission . PHP_EOL; 47 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 48 | */ 49 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 50 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 51 | /* 52 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 53 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 54 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 55 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 56 | 57 | echo "Available cars are " . Car::$counter . PHP_EOL; 58 | */ 59 | /* 60 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 61 | 62 | $car->start(); 63 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 64 | $car->stop(); 65 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 66 | */ 67 | /* 68 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 69 | 70 | $car->changeSpeed(65); 71 | $car->applyBreak(); 72 | $car->changeGear(4); 73 | $car->changeSpeed(75); 74 | $car->applyBreak(); 75 | */ 76 | 77 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 78 | 79 | $car->ownerName = 'John Doe'; 80 | echo " Owner: ". $car->ownerName . PHP_EOL; 81 | $car->year = 2015; 82 | echo " Year: ". $car->year . PHP_EOL; 83 | $car->wipers; 84 | $car->honk(); 85 | $car->honk('gently'); 86 | $car->honk('louder', 'siren'); 87 | -------------------------------------------------------------------------------- /Chapter05/Exercise5.10/Car.php: -------------------------------------------------------------------------------- 1 | hasKeyinIgnition) { 18 | $this->engineStatus = true; 19 | } 20 | } 21 | 22 | public function changeSpeed($speed) 23 | { 24 | echo "The car has been accelerated to " . $speed . " kph. " . PHP_EOL; 25 | } 26 | 27 | public function changeGear($gear) 28 | { 29 | echo "Shifted to gear number " . $gear . ". " . PHP_EOL; 30 | } 31 | 32 | public function applyBreak() 33 | { 34 | echo "All the 4 breaks in the wheels applied. " . PHP_EOL; 35 | } 36 | } 37 | /* 38 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 39 | echo "Vehicle Type: " . get_class($car) . PHP_EOL; 40 | echo " Make: " . $car->getMake() . PHP_EOL; 41 | echo " Model: " . $car->getModel() . PHP_EOL; 42 | echo " Color: " . $car->getColor() . PHP_EOL; 43 | echo " No of wheels: " . $car->getNoOfWheels() . PHP_EOL; 44 | 45 | echo " No of Doors: " . $car->doors . PHP_EOL; 46 | echo " Transmission: " . $car->transmission . PHP_EOL; 47 | echo " Passenger capacity: " . $car->passengerCapacity . PHP_EOL; 48 | */ 49 | //echo " No of wheels: " . $car->noOfWheels . PHP_EOL; 50 | //echo " Engine number: " . $car->engineNumber . PHP_EOL; 51 | /* 52 | $car1 = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 53 | $car2 = new Car('Toyota', 'Allion', 'White', 4, '24CJ4568'); 54 | $car3 = new Car('Hyundai', 'Elantra', 'Black', 4, '24CJ1234'); 55 | $car4 = new Car('Chevrolet', 'Camaro', 'Yellow', 4, '23CJ9397'); 56 | 57 | echo "Available cars are " . Car::$counter . PHP_EOL; 58 | */ 59 | /* 60 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 61 | 62 | $car->start(); 63 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 64 | $car->stop(); 65 | echo "The car is " . ($car->getEngineStatus() ? 'running' : 'stopped') . PHP_EOL; 66 | */ 67 | /* 68 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 69 | 70 | $car->changeSpeed(65); 71 | $car->applyBreak(); 72 | $car->changeGear(4); 73 | $car->changeSpeed(75); 74 | $car->applyBreak(); 75 | */ 76 | /* 77 | $car = new Car('Honda', 'Civic', 'Red', 4, '23CJ4567'); 78 | 79 | $car->ownerName = 'John Doe'; 80 | echo " Owner: ". $car->ownerName . PHP_EOL; 81 | $car->year = 2015; 82 | echo " Year: ". $car->year . PHP_EOL; 83 | $car->wipers; 84 | $car->honk(); 85 | $car->honk('gently'); 86 | $car->honk('louder', 'siren'); 87 | */ --------------------------------------------------------------------------------