PHP-Einführung - Lesson 4 - Object Oriented Programming Alexander Lichter June 27, 2017
Content of this lesson 1. Recap 2. Why OOP? 3. Git gud - PHPStorm 4. Include and Require 5. Classes and objects 6. Method chaining 7. Magic methods 1
Recap
A short recap (again) Last lesson we learned a lot about form handling, sanitizing, validating input and about the HTTP protocol. 2
A short recap (again) Last lesson we learned a lot about form handling, sanitizing, validating input and about the HTTP protocol. A note on form validation itself: What we did was only server-side validation. You can do a client-side form validation with HTML5 and JS, but that s not part of this course. 2
A short recap (again) Last lesson we learned a lot about form handling, sanitizing, validating input and about the HTTP protocol. A note on form validation itself: What we did was only server-side validation. You can do a client-side form validation with HTML5 and JS, but that s not part of this course. We now can handle user input and are almost ready to build huge applications. But when we have a lot of code (30k+ Lines of Code), we should structure it well. We will learn how to program object oriented therefore! 2
Why OOP?
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: 3
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: Well-structured 3
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: Well-structured Without duplicates [DRY] 3
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: Well-structured Without duplicates [DRY] Flexible, maintainable and changeable with ease 3
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: Well-structured Without duplicates [DRY] Flexible, maintainable and changeable with ease Modularized 3
Why we need OOP As you may know from the SWT lecture, OOP is mainly used while programming high-level-languages (exceptions are there [Haskell]). Your future code should be: Well-structured Without duplicates [DRY] Flexible, maintainable and changeable with ease Modularized And OOP gives us all those points when used correctly. 3
Git gud - PHPStorm
Why we need OOP In the next weeks we will develop more and more complex programs. 4
Why we need OOP In the next weeks we will develop more and more complex programs. To have some QoL features on your side (Autocomplete, Error hinting and more), you should get yourself an IDE. I already mentioned that in the 1st lesson. 4
Why we need OOP In the next weeks we will develop more and more complex programs. To have some QoL features on your side (Autocomplete, Error hinting and more), you should get yourself an IDE. I already mentioned that in the 1st lesson. My IDE of choice is PHPStorm You can get a free copy with your TU Dresden mail on https://www.jetbrains.com/student/. Download it now and we will set the IDE up together! 4
Include and Require
Include/Require To structure your PHP code even better, you can (and should!) put it in different files. There are two methods to include these files in your main file, called include and require. Imagine you want to welcome every user when the opens a page of your website. You d declare a welcome function/text in the welcome.php and can include it on every page like that: 5
Include/Require To structure your PHP code even better, you can (and should!) put it in different files. There are two methods to include these files in your main file, called include and require. Imagine you want to welcome every user when the opens a page of your website. You d declare a welcome function/text in the welcome.php and can include it on every page like that: 1 <?php 2 i n c l u d e r e l a t e / path / to / welcome. php ; 3 // i n c l u d e welcome. php ; when i n same f o l d e r 4 // Page c o n t e n t h e r e 5 5
Include/Require - Difference and once When the file you want to include couldn t be found, include will throw a warning (but the script continues working). Require would throw a fatal error instead, making the script halt instantly. This is the only difference 6
Include/Require - Difference and once When the file you want to include couldn t be found, include will throw a warning (but the script continues working). Require would throw a fatal error instead, making the script halt instantly. This is the only difference That means, require should be used for critical/important files. 6
Include/Require - Difference and once When the file you want to include couldn t be found, include will throw a warning (but the script continues working). Require would throw a fatal error instead, making the script halt instantly. This is the only difference That means, require should be used for critical/important files. There are also two methods called include once and require once. They work like include/require but only include a file once. When it should be included again, the methods won t do that. That s good for including functions/modularized code, but bad for templating. 6
Classes and objects
Classes and objects - theory Before we go deeper into the practical OOP part, let s talk about some terms everyone of you should know: Classes and Objects. 7
Classes and objects - theory Before we go deeper into the practical OOP part, let s talk about some terms everyone of you should know: Classes and Objects. To avoid complex explanations and abstractions, here is a simple explanation for both terms: 7
Classes and objects - theory Before we go deeper into the practical OOP part, let s talk about some terms everyone of you should know: Classes and Objects. To avoid complex explanations and abstractions, here is a simple explanation for both terms: You can imagine a class as a blueprint, for a house for example. It defines the structure, the shape, hold relationships between the parts (for example that the living room is connected to the bath) and is defined, even when the house isn t built up. 7
Classes and objects - theory Before we go deeper into the practical OOP part, let s talk about some terms everyone of you should know: Classes and Objects. To avoid complex explanations and abstractions, here is a simple explanation for both terms: You can imagine a class as a blueprint, for a house for example. It defines the structure, the shape, hold relationships between the parts (for example that the living room is connected to the bath) and is defined, even when the house isn t built up. An object can be understood as the real house then! It stores all the data that is needed for the house, like the floor type or the wall colors. 7
Classes and objects - theory Before we go deeper into the practical OOP part, let s talk about some terms everyone of you should know: Classes and Objects. To avoid complex explanations and abstractions, here is a simple explanation for both terms: You can imagine a class as a blueprint, for a house for example. It defines the structure, the shape, hold relationships between the parts (for example that the living room is connected to the bath) and is defined, even when the house isn t built up. An object can be understood as the real house then! It stores all the data that is needed for the house, like the floor type or the wall colors. 7
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? 8
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? No! 2. Can a class exist without an object? 8
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? No! 2. Can a class exist without an object? Yes, that works! 3. Can there be more than one object of a specific class? 8
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? No! 2. Can a class exist without an object? Yes, that works! 3. Can there be more than one object of a specific class? Yup, that s no problem! 4. Can an object have multiple classes? 8
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? No! 2. Can a class exist without an object? Yes, that works! 3. Can there be more than one object of a specific class? Yup, that s no problem! 4. Can an object have multiple classes? Nope, that s not possible like this. The only way is Inheritance, but more about it later 8
Classes and objects - questions Now some questions for you. In case you don t understand something or anything seems not logical, do not hesitate to tell it! 1. Can an object exist without a class? No! 2. Can a class exist without an object? Yes, that works! 3. Can there be more than one object of a specific class? Yup, that s no problem! 4. Can an object have multiple classes? Nope, that s not possible like this. The only way is Inheritance, but more about it later Alright, I think you catched the drift! 8
Classes and objects - basic class So, how does classes and objects look in PHP: 9
Classes and objects - basic class So, how does classes and objects look in PHP: 1 <?php 2 3 c l a s s House 4 { 5 p u b l i c $rooms = 4 ; 6 p u b l i c $ s t r e e t = Am K l e i n e n Anger 13 ; 7 } 8 10 9 $ o b j = new House ; 11 echo <pre> ; 12 var dump ( $ o b j ) ; 13 echo <br> ; 14 echo $obj >rooms ; // Output t h e room number 9
Classes and objects - basic class So, how does classes and objects look in PHP: 1 <?php 2 3 c l a s s House 4 { 5 p u b l i c $rooms = 4 ; 6 p u b l i c $ s t r e e t = Am K l e i n e n Anger 13 ; 7 } 8 10 9 $ o b j = new House ; 11 echo <pre> ; 12 var dump ( $ o b j ) ; 13 echo <br> ; 14 echo $obj >rooms ; // Output t h e room number As you see, var dump shows the class and the properties of the object 9
Classes and objects - getter and setter It is a bad practice to access variables directly. We use getter and setter to access them. 10
Classes and objects - getter and setter It is a bad practice to access variables directly. We use getter and setter to access them. 1 <?php 2 c l a s s House 3 { 4 p u b l i c $rooms = 4 ; // C l a s s p r o p e r t y 5 p u b l i c $ s t r e e t = Am K l e i n e n Anger 13 ; 6 7 p u b l i c f u n c t i o n getrooms ( ) { 8 r e t u r n $ t h i s >rooms ; // To r e f e r to t h e c l a s s i t s e l f i n t h e c l a s s, use $ t h i s 9 } 10 11 p u b l i c f u n c t i o n s setrooms ( $rooms ) { 12 $ t h i s >rooms = ( i n t ) $rooms ; // V a l i d a t i o n! 13 } 14 } 15 16 $h = new House ( ) ; // same as new House ;, but t h i s one i s b e t t e r! 10
Classes and objects - getter and setter #2 Now we can alter the property rooms through it s get and set methods: 11
Classes and objects - getter and setter #2 Now we can alter the property rooms through it s get and set methods: 1 echo $h >getrooms ( ) ; //4 2 $h >setrooms ( 1 0 ) ; 3 echo $h >getrooms ( ) ; // 10 11
Classes and objects - getter and setter #2 Now we can alter the property rooms through it s get and set methods: 1 echo $h >getrooms ( ) ; //4 2 $h >setrooms ( 1 0 ) ; 3 echo $h >getrooms ( ) ; // 10 Furthermore it is no problem to create objects from the same class with different properties/attributes: 11
Classes and objects - getter and setter #2 Now we can alter the property rooms through it s get and set methods: 1 echo $h >getrooms ( ) ; //4 2 $h >setrooms ( 1 0 ) ; 3 echo $h >getrooms ( ) ; // 10 Furthermore it is no problem to create objects from the same class with different properties/attributes: 1 $house = new House ( ) ; 2 $ v i l l a = new House ( ) ; 3 $house >setrooms ( 5 ) ; 4 $ v i l l a >setrooms ( 1 0 ) ; 5 echo $ v i l l a >getrooms ( ). <br> 6. $house >getrooms ( ) ; 7 11
A simple task for the beginning Are you ready to program some OOP things? Great! 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU RAM size (in GB) 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU RAM size (in GB) OS 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU RAM size (in GB) OS Use getter and setter and keep DRY. 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU RAM size (in GB) OS Use getter and setter and keep DRY. Furthermore, create a form where the user can input those information. Don t forget to validate and sanitize those! 12
A simple task for the beginning Are you ready to program some OOP things? Great! Your first task is to create a class of the type PC. Think about (but not only about): PC-Type [Laptop, Tower, Server] CPU CPU cores GPU RAM size (in GB) OS Use getter and setter and keep DRY. Furthermore, create a form where the user can input those information. Don t forget to validate and sanitize those! BONUS: Use server- and client-side validation ;) 12
Method chaining
Method chaining Method chaining is a great concept to reduce your code to a minimum by.. chaining methods. But how does it work? 13
Method chaining Method chaining is a great concept to reduce your code to a minimum by.. chaining methods. But how does it work? 1 c l a s s Gameboy { 2 p u b l i c $ b a t t e r y ; 3 p u b l i c l o a d P e r M i n u t e = 0. 0 8 ; 4 p u b l i c d r a i n P e r M i n u t e = 0. 2 ; 5 6 p u b l i c f u n c t i o n l o a d ( $minutes ) 7 { 8 $ t h i s >b a t t e r y += $minutes $ t h i s >l o a d P e r M i n u t e ; 9 //Don t use g e t t e r s / s e t t e r s i n s i d e t h e c l a s s 10 i f ( $ t h i s >b a t t e r y > 100) { $ t h i s >b a t t e r y = 1 0 0 ; } 11 r e t u r n $ t h i s ; // I m p o r t a n t f o r c h a i n i n g! 12 } 13 p u b l i c f u n c t i o n p l a y ( $minutes ) 14 { 15 $ t h i s >b a t e r y = $minutes $ t h i s >d r a i n P e r M i n u t e ; 16 r e t u r n $ t h i s ; // Implement v a l i d a t i o n as i n l o a d! 17 } 18 // G e t t e r and s e t t e r h e r e ; ) 19 } 13
Method chaining continued Now we can easily find out how much battery is left: 14
Method chaining continued Now we can easily find out how much battery is left: 1 $ g b C o l o r = new Gameboy ( ) ; 2 3 echo $gbcolor >l o a d (10 60) >p l a y ( 1 4 0 ) >g e t B a t t e r y ( ) ; 4 // Load f o r 10 hours, then p l a y f o r 140 m i n u t e s 14
Method chaining continued Now we can easily find out how much battery is left: 1 $ g b C o l o r = new Gameboy ( ) ; 2 3 echo $gbcolor >l o a d (10 60) >p l a y ( 1 4 0 ) >g e t B a t t e r y ( ) ; 4 // Load f o r 10 hours, then p l a y f o r 140 m i n u t e s How it works: By returning this (the object itself) in every method, you can use the return value of each method to issue the next one on the (now altered) object. 14
Method chaining continued Now we can easily find out how much battery is left: 1 $ g b C o l o r = new Gameboy ( ) ; 2 3 echo $gbcolor >l o a d (10 60) >p l a y ( 1 4 0 ) >g e t B a t t e r y ( ) ; 4 // Load f o r 10 hours, then p l a y f o r 140 m i n u t e s How it works: By returning this (the object itself) in every method, you can use the return value of each method to issue the next one on the (now altered) object. This does not work for all methods! 14
Magic methods
Magic methods - General So, you may ask yourselves: What are magic methods? 15
Magic methods - General So, you may ask yourselves: What are magic methods? Well, they behave a bit like superglobals: You do not need to declare them by yourself and they are available almost everywhere. 15
Magic methods - General So, you may ask yourselves: What are magic methods? Well, they behave a bit like superglobals: You do not need to declare them by yourself and they are available almost everywhere. The difference is, that you can only use them in classes! We will learn more about three more or less important magic methods: 15
Magic methods - General So, you may ask yourselves: What are magic methods? Well, they behave a bit like superglobals: You do not need to declare them by yourself and they are available almost everywhere. The difference is, that you can only use them in classes! We will learn more about three more or less important magic methods: construct() destruct() tostring() 15
Magic methods - Constructor 1 <?php 2 c l a s s Person 3 { 4 p u b l i c $name ; 5 p u b l i c $age ; 6 p u b l i c $ s e x ; // bool, t r u e = male 7 8 // C a l l e d on c l a s s c o n s t r u c t i o n 9 //Can be used to s e t p r o p e r t i e s 10 p u b l i c f u n c t i o n c o n s t r u c t ( $name, $age, $ s e x ) { 11 $ t h i s >name = $name ; 12 $ t h i s >age = $age ; 13 $ t h i s >s e x = $ s e x ; 14 } 15 } 16 17 $ s i e g f r i e d = new Person ( S i e g f r i e d, 35, t r u e ) ; 18 $ l i n d a = new Person ( Linda, 19, f a l s e ) ; 19 var dump ( $ s i e g f r i e d, $ l i n d a ) ; 16
Magic methods - Destructor 1 <?php 2 c l a s s D e s t r u c t i o n { 3 f u n c t i o n c o n s t r u c t ( ) { 4 p r i n t We a r e i n t h e c o n s t r u c t o r now <br> ; 5 } 6 7 f u n c t i o n d e s t r u c t ( ) { 8 p r i n t D e s t r o y i n g t h e c l a s s now <br> ; 9 } 10 } 11 12 $ o b j = new D e s t r u c t i o n ( ) ; 13 $ a n o t h e r = new D e s t r u c t i o n ( ) ; 14 u n s e t ( $ a n o t h e r ) ; // D e s t r o y s o b j. 15 echo EOF ; 16?> The destructor is the opposite of the constructor and is executed when the object is destroyed (EOF or unset eg.) 17
Magic methods - tostring 1 <?php 2 c l a s s Person 3 { 4 p u b l i c $name ; 5 p u b l i c $age ; 6 p u b l i c $ s e x ; // bool, t r u e = male 7 8 p u b l i c f u n c t i o n t o S t r i n g ( ) { 9 $ s e x S t r i n g = $ s e x? Male : Female ; // Ternary o p e r a t o r 10 r e t u r n $name i s $age y e a r s o l d and $ s e x S t r i n g ; 11 } 12 } 13 14 $randomperson = new Person ( ) ; 15 $randomperson >name = Randy ; 16 $randomperson >age = 1 9 ; 17 $randomperson >s e x = t r u e ; 18 19 echo $randomperson ; 18
Your turn again! Alright! You got a new IDE and some more knowledges. Now it s time to prove it 19
Your turn again! Alright! You got a new IDE and some more knowledges. Now it s time to prove it Write a class Car that models the car itself (seat count, steering wheel side, type, tank). It should be possible fill the tank and to ride the car. Use method chaining when possible. Print out all important information when you use echo $object (while $object has the type Car) Good Luck 19