Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

What?

Slide 3

Slide 3 text

What is OOP? Object orientation is the computer science of long words lornajane

Slide 4

Slide 4 text

OOP Glossary • methods these are functions. Seriously • properties these are variables • class recipe for making an object • object cool thing with its own properties and methods

Slide 5

Slide 5 text

Why?

Slide 6

Slide 6 text

Encapsulation In OOP: • array indexes become “properties” • functions lose their prefix and become “methods” An object contains both data and functionality

Slide 7

Slide 7 text

Encapsulation Imagine an array of data $date = array("hours" => "14", "minutes" => "36", "timezone" => "Europe/Amsterdam"); And some functions date_get_timestamp($date); date_get_time($date); date_get_datetime_in_timezone($date, $tz);

Slide 8

Slide 8 text

Autoloading Code in classes can be autoloaded. This means: • you will never write another require() statement • only the code actually needed will ever be parsed

Slide 9

Slide 9 text

How Autoloading Works

Slide 10

Slide 10 text

Prerequisites for Autoloading • one class per file • very predictable mapping from namespaced classname to file location • e.g. \MyLib\User lives in lib/MyLib/User.php For more details, see PSR4: http://www.php-fig.org/psr/psr-4/

Slide 11

Slide 11 text

Write an Autoloader Write a function which accepts the classname and includes the relevant file. To tell PHP about your autoloader: spl_autoload_register("my_autoload_func");

Slide 12

Slide 12 text

Extendable We can take an object, and just change one bit or add something, without copy pasting. The keyword is “inheritance”

Slide 13

Slide 13 text

Inheritance Take this ClickableButton class and make it go ping when clicked. class PingingButton extends ClickableButton Our new class gets everything that was in ClickableButton and we can add/override as we wish

Slide 14

Slide 14 text

Pluggable Code expecting one type of object can easily accept a similar one. We can extend or replace objects without changing the code that handles it.

Slide 15

Slide 15 text

How?

Slide 16

Slide 16 text

Start With a Class We’ll create a class with properties and methods.

Slide 17

Slide 17 text

PHP User Class Start by declaring the class and its properties … 1 class User { 2 protected $username; 3 protected $email;

Slide 18

Slide 18 text

PHP User Class … next the constructor … 1 public function __construct($username) { 2 // lookup table for people's details 3 $people = [ 4 "lornajane" => "[email protected]", 5 "crell" => "larry@...", 6 "emmajanehw" => "emma@..." 7 ]; 8 9 $this->username = $username; 10 $this->email = $people[$username]; 11 12 }

Slide 19

Slide 19 text

PHP User Class … and a couple of other methods 1 public function getUsername() { 2 return $this->username; 3 } 4 5 public function getGravatar() { 6 $url = "http://www.gravatar.com/avatar/" 7 . md5($this->email); 8 return ""; 9 } 10 }

Slide 20

Slide 20 text

How to Use a Class First we need to require or autoload the code. Then we instantiate the object.

Slide 21

Slide 21 text

Autoloader spl_autoload_register(function ($classname) { require __DIR__ . '/../inc/' . $classname . '.php'; });

Slide 22

Slide 22 text

Instantiate a User Object Create an object by using the new keyword $user = new User("lornajane");

Slide 23

Slide 23 text

User Object in a Template This is what I have in my template file getGravatar()?> Hi, getUsername()?>

Slide 24

Slide 24 text

Project Overview . ├── inc │ └── User.php ├── public │ └── index.php ├── README.md └── templates ├── footer.php ├── greet.php ├── header.php └── login.php

Slide 25

Slide 25 text

Look What We Made

Slide 26

Slide 26 text

Look What We Made

Slide 27

Slide 27 text

And Breathe

Slide 28

Slide 28 text

Other Cool OOP Things • inheritance • namespaces • interfaces • exceptions

Slide 29

Slide 29 text

Inheritance We have a User class. How about something a little more specific? 1 class AdminUser extends User { 2 public function getUsername() { 3 $name = parent::getUsername(); 4 return $name . " (admin)"; 5 } 6 }

Slide 30

Slide 30 text

Use the Admin Class If the user ticked the box, we stored that too 1 if($_SESSION['admin']) { 2 $user = new AdminUser($_SESSION['username']); 3 } else { 4 $user = new User($_SESSION['username']); 5 }

Slide 31

Slide 31 text

Now Look

Slide 32

Slide 32 text

Now Look

Slide 33

Slide 33 text

What About StdClass? The StdClass class is just the parent of all other objects in PHP It’s better to declare a class for a specific use

Slide 34

Slide 34 text

Namespaces Namespaces allow us to separate our code, and use multiple libraries

Slide 35

Slide 35 text

Namespaces We change class declarations and rename files to match inc/User.php becomes inc/User/User.php namespace User; class User { inc/AdminUser.php becomes inc/User/Admin.php namespace User; class Admin extends User {

Slide 36

Slide 36 text

Project Overview . ├── inc │ ├── Animal │ │ └── Cat.php │ └── User │ ├── Admin.php │ └── User.php ├── public │ └── index.php ├── README.md └── templates └── ...

Slide 37

Slide 37 text

Namespaces The autoloader needs to change as well 1 spl_autoload_register(function ($classname) { 2 require __DIR__ . '/../inc/' 3 . str_replace('\\', DIRECTORY_SEPARATOR, $classname) 4 . '.php'; 5 });

Slide 38

Slide 38 text

Namespaces We also need to give the qualified name of the object when instantiating it: $user = new \User\User("lornajane");

Slide 39

Slide 39 text

Namespaces New classes can go into new namespaces 1 namespace Animal; 2 3 class Cat { 4 protected $username; 5 protected $email; 6 7 public function __construct() { 8 // I only know one cat 9 $this->username = "orbit"; 10 $this->email = "[email protected]"; 11 }

Slide 40

Slide 40 text

Using Another Object Let’s instantiate and use some objects // featured users $featured = array( new \User\User("emmajanehw"), new \Animal\Cat());

Other Excellent Users Of This Site:

getGravatar()?> 

Slide 41

Slide 41 text

Showing Off Featured Users

Slide 42

Slide 42 text

Object Identity How can we check if an object has a getGravatar() method?

Slide 43

Slide 43 text

Object Identity How can we check if an object has a getGravatar() method? Check the object type with instanceof • but one is a Cat and one is a User, and what if we add more types?

Slide 44

Slide 44 text

Interfaces An interface is a contract. It defines what an object can do. We could make a Picturesque interface interface Picturesque { public function getGravatar(); } Good news: autoloading works for interfaces!

Slide 45

Slide 45 text

Interfaces A Class an implement an interface. Class Cat implements Picturesque If it does, it MUST have all the methods defined exactly as in the interface. (ours already do)

Slide 46

Slide 46 text

Object Identity How can we check if an object has a getGravatar() method? Check the object type with instanceof • but one is a Cat and one is a User, and what if we add more types?

Slide 47

Slide 47 text

Object Identity How can we check if an object has a getGravatar() method? Check the object type with instanceof • but one is a Cat and one is a User, and what if we add more types? Only accept objects which implement the Picturesque interface

Slide 48

Slide 48 text

TypeHinting How to require that a particular interface is used function addFeaturedUser(Picturesque $user) { return $user; } Adapt our code to use this function // featured users $featured[] = addFeaturedUser(new \User\User("emmajanehw")); $featured[] = addFeaturedUser(new \Animal\Cat());

Slide 49

Slide 49 text

Exceptions Exceptions are: • beautiful errors • objects • opportunities

Slide 50

Slide 50 text

Exceptions in PHP Exceptions are Objects; they can be extended PHP itself throws exceptions: $db = new PDO("foo", "bar"); PHP Fatal error: Uncaught exception ‘PDOExceptio with message ‘invalid data source name’

Slide 51

Slide 51 text

Exceptions in PHP We should catch exceptions: 1 try { 2 // success case code goes here 3 $db = new PDO("foo", "bar"); 4 } catch(PDOException $e) { 5 echo "some DB fail occurred"; 6 }

Slide 52

Slide 52 text

Throwing Exceptions function addTwoNumbers($a, $b) { if(($a == 0) || ($b == 0)) { throw new Exception("Zero is Boring!"); } return $a + $b; } echo addTwoNumbers(3,2); // 5 echo addTwoNumbers(5,0); // error!! Fatal error: Uncaught exception 'Exception' with message 'Zero is Boring!'

Slide 53

Slide 53 text

Extending Exceptions We can extend the Exception class for our own use 1 class DontBeDaftException extends Exception { 2 } 3 4 function inspectCurtains($colour) { 5 if($colour == "orange" || $colour == "spotty") { 6 throw new DontBeDaftException($colour . 'is daft'); 7 } 8 echo "The curtains are $colour\n"; 9 }

Slide 54

Slide 54 text

And Breathe

Slide 55

Slide 55 text

And Breathe (just one more thing)

Slide 56

Slide 56 text

Duplicate Functionality Did you notice that the getGravatar() method is identical in those unrelated classes?

Slide 57

Slide 57 text

Traits Traits are simply compiler-assisted copy/paste. Rasmus Lerdorf

Slide 58

Slide 58 text

Traits A trait looks a lot like a class, or a bit of one 1 trait Gravatar { 2 public function getGravatar() { 3 $url = "http://www.gravatar.com/avatar/" 4 . md5($this->email); 5 return ""; 6 } 7 } Good news: autoloading works for traits!

Slide 59

Slide 59 text

Traits Put a trait into your class with the use keyword: 1 namespace User; 2 3 class User implements \Picturesque { 4 protected $username; 5 protected $email; 6 7 use \Gravatar; 8 9 public function __construct($username) { 10 ....

Slide 60

Slide 60 text

Project Overview . ├── inc │ ├── Animal │ │ └── Cat.php │ ├── Gravatar.php │ ├── Picturesque.php │ └── User │ ├── Admin.php │ └── User.php ├── public │ └── index.php ├── README.md └── templates └── ...

Slide 61

Slide 61 text

That’s all, folks

Slide 62

Slide 62 text

TL;DR • class recipe for making an object • object an item with properties and methods • inheritance use one class as basis for another • interface contract agreeement for classes • typehinting how to identify a class • trait how to use the same functionality in two unrelated classes

Slide 63

Slide 63 text

Questions? (and resources) Intermediate PHP http://lrnja.net/php-video Contact me: @lornajane or http://lornajane.net

Slide 64

Slide 64 text

No content