OOP Is More Than Cars and Dogs

Chris Tankersley
Chris TankersleyPHP Programmer at Home
OOP is More Than Cars
and Dogs
Chris Tankersley
php[tek] 2015
php[tek] 2015 1
Who Am I
• PHP Programmer for over 10 years
• Work/know a lot of different
languages, even COBOL
• Primarily do Zend Framework 2
• https://github.com/dragonmantank
php[tek] 2015 2
Quick Vocabulary Lesson
• Class – Definition of code
• Object – Instantiation of a Class
• Member – Variable belonging to a class
• Method – Function belonging to a class
There will be more as we go along
php[tek] 2015 3
php[tek] 2015 4
Class
class Employee {
protected $name; // This is a member
protected $number;
// This is a Method
public function setData($data) {
$this->name = $data['name'];
$this->number = $data['number'];
}
public function viewData() {
echo <<<ENDTEXT
Name: {$this->name}
Number: {$this->number}
ENDTEXT;
}
}
Object
<?php
$manager= new Manager();
// ^
// |
// `--- This is the Object
php[tek] 2015 5
Why are we using OOP?
php[tek] 2015 6
Let’s count the reasons
• Because we’re told to, procedural programming leads to spaghetti
code
• We deal with objects every day, so it shouldn’t be too hard
• We want to allow for code re-use
• We want to group like code together
• We want to easily extend our code
• We want to be able to easily test our code
php[tek] 2015 7
Getting OOP Right is Complicated
php[tek] 2015 8
php[tek] 2015 9
php[tek] 2015 10
php[tek] 2015 11
php[tek] 2015 12
php[tek] 2015 13
php[tek] 2015 14
Can a Dog have Wheels?
• Discuss (or listen to me talk some more)
php[tek] 2015 15
Inheritance
php[tek] 2015 16
What we’re all taught
• Classes are “things” in the real world
• We should construct class members based on Attributes
• Number of wheels
• Sound it makes
• We should construct class methods based on “Actions”
• Running
• Speaking
• Jumping
php[tek] 2015 17
New Vocabulary
• Parent Class – Class that is extended
• Child Class – Class that is extending another class
In PHP, a class can be both a Child and a Parent at the same time
php[tek] 2015 18
Where I Learned It
php[tek] 2015 19
Our Structure
php[tek] 2015 20
Employee
Manager Scientist Laborer
The Employee Class
php[tek] 2015 21
abstract class Employee {
protected $name; // Employee Name
protected $number; // Employee Number
public function setData($data) {
$this->name = $data['name'];
$this->number = $data['number'];
}
public function viewData() {
echo <<<ENDTEXT
Name: {$this->name}
Number: {$this->number}
ENDTEXT;
}
}
The Manager Class
php[tek] 2015 22
class Manager extends Employee {
protected $title; // Employee Title
protected $dues; // Golf Dues
public function setData($data) {
parent::setData($data);
$this->title = $data['title'];
$this->dues = $data['dues'];
}
public function viewData() {
parent::viewData();
echo <<<ENDTEXT
Title: {$this->title}
Golf Dues: {$this->dues}
ENDTEXT;
}
}
The Scientist Class
php[tek] 2015 23
class Scientist extends Employee {
protected $pubs; // Number of Publications
public function setData($data) {
parent::setData($data);
$this->pubs = $data['pubs'];
}
public function viewData() {
parent::viewData();
echo <<<ENDTEXT
Publications: {$this->pubs}
ENDTEXT;
}
}
The Laborer Class
php[tek] 2015 24
class Laborer extends Employee {
}
What does this teach us?
• Inheritance
• Makes it easier to group code together and share it amongst classes
• Allows us to extend code as needed
• PHP allows Single inheritance
php[tek] 2015 25
We use it all the time
namespace ApplicationController;
use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;
Class IndexController extends AbstractActionController {
public function indexAction() {
/** @var VendorVendorService $vendor */
$vendor = $this->serviceLocator->get('VendorVendorService');
$view = new ViewModel();
return $view;
}
} php[tek] 2015 26
Why it Works (Most of the time, Kinda)
• Allows us to extend things we didn’t necessarily create
• Encourages code re-use
• Allows developers to abstract away things
php[tek] 2015 27
How to use it
• Understand the difference between Public, Protected, and Private
• Public – Anyone can use this, even children
• Protected – Anything internal can use this, even children
• Private – This is mine, hands off
• Abstract vs Concrete Classes
• Abstract classes cannot be instantiated directly, they must be extended
php[tek] 2015 28
The Employee Class
php[tek] 2015 29
abstract class Employee {
protected $name; // Employee Name
protected $number; // Employee Number
public function setData($data) {
$this->name = $data['name'];
$this->number = $data['number'];
}
public function viewData() {
echo <<<ENDTEXT
Name: {$this->name}
Number: {$this->number}
ENDTEXT;
}
}
The Manager Class
php[tek] 2015 30
class Manager extends Employee {
protected $title; // Employee Title
protected $dues; // Golf Dues
public function setData($data) {
parent::setData($data);
$this->title = $data['title'];
$this->dues = $data['dues'];
}
public function viewData() {
parent::viewData();
echo <<<ENDTEXT
Title: {$this->title}
Golf Dues: {$this->dues}
ENDTEXT;
}
}
An Example
// Fatal error: Cannot instantiate abstract class Employee
$employee = new Employee();
// We can do this though!
$manager = new Manager();
// Fatal error: Cannot access protected property Manager::$name
$manager->name = 'Bob McManager’;
// setData is public, so we can use that
$manager->setData(['name' => 'Bob McManager’,'number' => 1]);
// We can also view the data, since it's public
$manager->viewData();
php[tek] 2015 31
Why can Inheritance Be Bad
• PHP only allows Single Inheritance on an Class
• You can have a series of Inheritance though, for example CEO extends
Manager, Manager extends Employee
• Long inheritance chains can be a code smell
• Private members and methods cannot be used by Child classes
• Single Inheritance can make it hard to ‘bolt on’ new functionality
between disparate classes
php[tek] 2015 32
Composition over Inheritance
php[tek] 2015 33
The General Idea
• Classes contain other classes to do work and extend that way, instead
of through Inheritance
• Interfaces define “contracts” that objects will adhere to
• Your classes implement interfaces to add needed functionality
php[tek] 2015 34
Interfaces
interface EmployeeInterface {
protected $name;
protected $number;
public function getName();
public function setName($name);
public function getNumber();
public function setNumber($number);
}
interface ManagerInterface {
protected $golfHandicap;
public function getHandicap();
public function setHandicap($handicap);
}
php[tek] 2015 35
Interface Implementation
class Employee implements EmployeeInterface {
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
class Manager implements EmployeeInterface, ManagerInterface {
// defines the employee getters/setters as well
public function getHandicap() {
return $this->handicap;
}
public function setHandicap($handicap) {
$this->handicap = $handicap;
}
}
php[tek] 2015 36
This is Good and Bad
• “HAS-A” is tends to be more flexible than “IS-A”
• Somewhat easier to understand, since there isn’t a hierarchy you
have to backtrack
• Each class must provide their own Implementation, so can lead to
code duplication
php[tek] 2015 37
Traits
• Allows small blocks of code to be defined that can be used by many
classes
• Useful when abstract classes/inheritance would be cumbersome
• My Posts and Pages classes shouldn’t need to extend a Slugger class just to
generate slugs.
php[tek] 2015 38
Avoid Code-Duplication with Traits
trait EmployeeTrait {
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
class Employee implements EmployeeInterface {
use EmployeeTrait;
}
class Manager implements EmployeeInterface, ManagerInterface {
use EmployeeTrait;
use ManagerTrait;
}
php[tek] 2015 39
Taking Advantage of OOP
php[tek] 2015 40
Coupling
php[tek] 2015 41
What is Coupling?
• Coupling is how dependent your code is on another class
• The more classes you are coupled to, the more changes affect your
class
php[tek] 2015 42
namespace ApplicationController;
use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;
class MapController extends AbstractActionController
{
public function indexAction()
{
// Position is an array with a Latitude and Longitude object
$position = $this->getServiceLocator()->get('MapService’)
->getLatLong('123 Main Street', 'Defiance', 'OH');
echo $position->latitude->getPoint();
}
}
php[tek] 2015 43
Law of Demeter
php[tek] 2015 44
Dependency Injection
php[tek] 2015 45
What is Dependency Injection?
• Injecting dependencies into classes, instead of having the class create
it
• Allows for much easier testing
• Allows for a much easier time swapping out code
• Reduces the coupling that happens between classes
php[tek] 2015 46
Method Injection
class MapService {
public function getLatLong(GoogleMaps $map, $street, $city, $state) {
return $map->getLatLong($street . ' ' . $city . ' ' . $state);
}
public function getAddress(GoogleMaps $map, $lat, $long) {
return $map->getAddress($lat, $long);
}
}
php[tek] 2015 47
Constructor Injection
class MapService {
protected $map;
public function __construct(GoogleMaps $map) {
$this->map = $map;
}
public function getLatLong($street, $city, $state) {
return $this
->map
->getLatLong($street . ' ' . $city . ' ' . $state);
}
}
php[tek] 2015 48
Setter Injection
class MapService {
protected $map;
public function setMap(GoogleMaps $map) {
$this->map = $map;
}
public function getMap() {
return $this->map;
}
public function getLatLong($street, $city, $state) {
return $this->getMap()->getLatLong($street . ' ' . $city . ' ' . $state);
}
}
php[tek] 2015 49
Single Responsibility Principle
php[tek] 2015 50
Single Responsibility Principle
• Every class should have a single responsibility, and that responsibility
should be encapsulated in that class
php[tek] 2015 51
What is a Responsibility?
• Responsibility is a “Reason To Change” – Robert C. Martin
• By having more than one “Reason to Change”, code is harder to
maintain and becomes coupled
• Since the class is coupled to multiple responsibilities, it becomes
harder for the class to adapt to any one responsibility
php[tek] 2015 52
An Example
/**
* Create a new invoice instance.
*
* @param LaravelCashierContractsBillable $billable
* @param object
* @return void
*/
public function __construct(BillableContract $billable, $invoice)
{
$this->billable = $billable;
$this->files = new Filesystem;
$this->stripeInvoice = $invoice;
}
/**
* Create an invoice download response.
*
* @param array $data
* @param string $storagePath
* @return SymfonyComponentHttpFoundationResponse
*/
public function download(array $data, $storagePath = null)
{
$filename = $this->getDownloadFilename($data['product']);
$document = $this->writeInvoice($data, $storagePath);
$response = new Response($this->files->get($document), 200, [
'Content-Description' => 'File Transfer',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
'Content-Transfer-Encoding' => 'binary',
'Content-Type' => 'application/pdf',
]);
$this->files->delete($document);
return $response;
}
php[tek] 2015 53
https://github.com/laravel/cashier/blob/master/src/Laravel/Cashier/Invoice.php
Why is this Bad?
• This single class has the following responsibilities:
• Generating totals for the invoice (including discounts/coupons)
• Generating an HTML View of the invoice (Invoice::view())
• Generating a PDF download of the invoice(Invoice::download())
• This is coupled to a shell script as well
• Two different displays handled by the class. Adding more means more
responsibility
• Coupled to a specific HTML template, the filesystem, the Laravel
Views system, and PhantomJS via the shell script
php[tek] 2015 54
How to Improve
• Change responsibility to just building the invoice data
• Move the ‘output’ stuff to other classes
php[tek] 2015 55
Unit Testing
php[tek] 2015 56
[Could not afford licensing fee for Grumpy Testing Picture]
php[tek] 2015 57
This is not a testing talk
• Using Interfaces makes it easier to mock objects
• Reducing coupling and following Demeter’s Law makes you have to
mock less objects
• Dependency Injection means you only mock what you need for that
test
• Single Responsibility means your test should be short and sweet
• Easier testing leads to more testing
php[tek] 2015 58
Final Thoughts
php[tek] 2015 59
We can make a dog with wheels!
• Abstract class for Animal
• Class for Dog that extends Animal
• Trait for Wheels
• With the write methodology, we could even unit test this
In the real world, we can now represent a crippled dog
php[tek] 2015 60
Here’s a cute dog instead
php[tek] 2015 61
Thank You!
http://ctankersley.com
chris@ctankersley.com
@dragonmantank
https://joind.in/13731
php[tek] 2015 62
Photos
• Slide 9 - http://bit.ly/1dkaoxS
• Slide 10 - http://bit.ly/1c4Gc8z
• Slide 11 - http://bit.ly/1R3isBp
• Slide 12 - http://bit.ly/1ScEWRZ
• Slide 13 - http://bit.ly/1Bc0qUv
• Slide 14 - http://bit.ly/1ILhfNV
php[tek] 2015 63
1 of 63

Recommended

OOP Is More Then Cars and Dogs - Midwest PHP 2017 by
OOP Is More Then Cars and Dogs - Midwest PHP 2017OOP Is More Then Cars and Dogs - Midwest PHP 2017
OOP Is More Then Cars and Dogs - Midwest PHP 2017Chris Tankersley
608 views63 slides
Coming to Terms with OOP In Drupal - php[world] 2016 by
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Chris Tankersley
387 views57 slides
PHPID online Learning #6 Migration from procedural to OOP by
PHPID online Learning #6 Migration from procedural to OOPPHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOPAchmad Mardiansyah
355 views32 slides
Dependency Injection Smells by
Dependency Injection SmellsDependency Injection Smells
Dependency Injection SmellsMatthias Noback
9.2K views44 slides
Object Oriented PHP5 by
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
42.5K views79 slides
OOP is more than Cars and Dogs by
OOP is more than Cars and Dogs OOP is more than Cars and Dogs
OOP is more than Cars and Dogs Chris Tankersley
925 views55 slides

More Related Content

What's hot

OOP in PHP by
OOP in PHPOOP in PHP
OOP in PHPTarek Mahmud Apu
606 views37 slides
OOP Is More Than Cars and Dogs by
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsChris Tankersley
617 views64 slides
Object oreinted php | OOPs by
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
4.7K views29 slides
Building a Pyramid: Symfony Testing Strategies by
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
2.7K views64 slides
Advanced Php - Macq Electronique 2010 by
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
3.8K views88 slides
Object Oriented Programming with PHP 5 - More OOP by
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
5.8K views29 slides

What's hot(19)

Object oreinted php | OOPs by Ravi Bhadauria
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria4.7K views
Building a Pyramid: Symfony Testing Strategies by CiaranMcNulty
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty2.7K views
Object Oriented Programming with PHP 5 - More OOP by Wildan Maulana
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana5.8K views
OOP by thinkphp
OOPOOP
OOP
thinkphp8.1K views
Oop in-php by Rajesh S
Oop in-phpOop in-php
Oop in-php
Rajesh S677 views
Class 7 - PHP Object Oriented Programming by Ahmed Swilam
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam2.6K views
Object Oriented Programming With PHP 5 #2 by Wildan Maulana
Object Oriented Programming With PHP 5 #2Object Oriented Programming With PHP 5 #2
Object Oriented Programming With PHP 5 #2
Wildan Maulana3.2K views
Object oriented programming in php 5 by Sayed Ahmed
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed433 views
Why Your Test Suite Sucks - PHPCon PL 2015 by CiaranMcNulty
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
CiaranMcNulty1.2K views
Advanced PHP Simplified - Sunshine PHP 2018 by Mark Niebergall
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Mark Niebergall529 views
Object Oriented Programming in PHP by Lorna Mitchell
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell3.9K views

Similar to OOP Is More Than Cars and Dogs

PHP: 4 Design Patterns to Make Better Code by
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
1.2K views104 slides
Quality assurance for php projects with PHPStorm by
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
16.2K views65 slides
What's New In Laravel 5 by
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
2.2K views86 slides
Tackling Tech Debt with Rector by
Tackling Tech Debt with RectorTackling Tech Debt with Rector
Tackling Tech Debt with RectorMichele Orselli
24 views54 slides
PHP 5.3 Overview by
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
492 views38 slides
Php on the desktop and php gtk2 by
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2Elizabeth Smith
4.2K views33 slides

Similar to OOP Is More Than Cars and Dogs(20)

Quality assurance for php projects with PHPStorm by Michelangelo van Dam
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
Michelangelo van Dam16.2K views
What's New In Laravel 5 by Darren Craig
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
Darren Craig2.2K views
PHP 5.3 Overview by jsmith92
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92492 views
Php on the desktop and php gtk2 by Elizabeth Smith
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
Elizabeth Smith4.2K views
Dependency injection in Drupal 8 by Alexei Gorobets
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets3.8K views
Workshop quality assurance for php projects tek12 by Michelangelo van Dam
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT) by Mike Schinkel
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Mike Schinkel10.5K views
From framework coupled code to #microservices through #DDD /by @codelytv by CodelyTV
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
CodelyTV1.5K views
Migration from Procedural to OOP by GLC Networks
Migration from Procedural to OOP Migration from Procedural to OOP
Migration from Procedural to OOP
GLC Networks290 views
Drupaljam xl 2019 presentation multilingualism makes better programmers by Alexander Varwijk
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
Alexander Varwijk121 views
Workshop quality assurance for php projects - ZendCon 2013 by Michelangelo van Dam
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
Michelangelo van Dam21.5K views
Comparison of different access controls by Rashmi Nair
Comparison of different access controlsComparison of different access controls
Comparison of different access controls
Rashmi Nair851 views
Demystifying Object-Oriented Programming - PHP[tek] 2017 by Alena Holligan
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
Alena Holligan322 views
Take the Plunge with OOP from #pnwphp by Alena Holligan
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
Alena Holligan509 views

More from Chris Tankersley

Docker is Dead: Long Live Containers by
Docker is Dead: Long Live ContainersDocker is Dead: Long Live Containers
Docker is Dead: Long Live ContainersChris Tankersley
53 views52 slides
Bend time to your will with git by
Bend time to your will with gitBend time to your will with git
Bend time to your will with gitChris Tankersley
194 views73 slides
Using PHP Functions! (Not those functions, Google Cloud Functions) by
Using PHP Functions! (Not those functions, Google Cloud Functions)Using PHP Functions! (Not those functions, Google Cloud Functions)
Using PHP Functions! (Not those functions, Google Cloud Functions)Chris Tankersley
177 views72 slides
Dead Simple APIs with OpenAPI by
Dead Simple APIs with OpenAPIDead Simple APIs with OpenAPI
Dead Simple APIs with OpenAPIChris Tankersley
311 views63 slides
Killer Docker Workflows for Development by
Killer Docker Workflows for DevelopmentKiller Docker Workflows for Development
Killer Docker Workflows for DevelopmentChris Tankersley
159 views64 slides
You Got Async in my PHP! by
You Got Async in my PHP!You Got Async in my PHP!
You Got Async in my PHP!Chris Tankersley
164 views140 slides

More from Chris Tankersley(20)

Using PHP Functions! (Not those functions, Google Cloud Functions) by Chris Tankersley
Using PHP Functions! (Not those functions, Google Cloud Functions)Using PHP Functions! (Not those functions, Google Cloud Functions)
Using PHP Functions! (Not those functions, Google Cloud Functions)
Chris Tankersley177 views
Killer Docker Workflows for Development by Chris Tankersley
Killer Docker Workflows for DevelopmentKiller Docker Workflows for Development
Killer Docker Workflows for Development
Chris Tankersley159 views
Docker for Developers - PHP Detroit 2018 by Chris Tankersley
Docker for Developers - PHP Detroit 2018Docker for Developers - PHP Detroit 2018
Docker for Developers - PHP Detroit 2018
Chris Tankersley865 views
BASHing at the CLI - Midwest PHP 2018 by Chris Tankersley
BASHing at the CLI - Midwest PHP 2018BASHing at the CLI - Midwest PHP 2018
BASHing at the CLI - Midwest PHP 2018
Chris Tankersley363 views
Docker for PHP Developers - php[world] 2017 by Chris Tankersley
Docker for PHP Developers - php[world] 2017Docker for PHP Developers - php[world] 2017
Docker for PHP Developers - php[world] 2017
Chris Tankersley821 views
Docker for PHP Developers - Madison PHP 2017 by Chris Tankersley
Docker for PHP Developers - Madison PHP 2017Docker for PHP Developers - Madison PHP 2017
Docker for PHP Developers - Madison PHP 2017
Chris Tankersley1.7K views
Docker for Developers - php[tek] 2017 by Chris Tankersley
Docker for Developers - php[tek] 2017Docker for Developers - php[tek] 2017
Docker for Developers - php[tek] 2017
Chris Tankersley1.1K views
From Docker to Production - SunshinePHP 2017 by Chris Tankersley
From Docker to Production - SunshinePHP 2017From Docker to Production - SunshinePHP 2017
From Docker to Production - SunshinePHP 2017
Chris Tankersley853 views
Docker for Developers - Sunshine PHP by Chris Tankersley
Docker for Developers - Sunshine PHPDocker for Developers - Sunshine PHP
Docker for Developers - Sunshine PHP
Chris Tankersley812 views
How We Got Here: A Brief History of Open Source by Chris Tankersley
How We Got Here: A Brief History of Open SourceHow We Got Here: A Brief History of Open Source
How We Got Here: A Brief History of Open Source
Chris Tankersley382 views
Docker for PHP Developers - ZendCon 2016 by Chris Tankersley
Docker for PHP Developers - ZendCon 2016Docker for PHP Developers - ZendCon 2016
Docker for PHP Developers - ZendCon 2016
Chris Tankersley565 views
From Docker to Production - ZendCon 2016 by Chris Tankersley
From Docker to Production - ZendCon 2016From Docker to Production - ZendCon 2016
From Docker to Production - ZendCon 2016
Chris Tankersley399 views

Recently uploaded

Special_edition_innovator_2023.pdf by
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdfWillDavies22
17 views6 slides
Scaling Knowledge Graph Architectures with AI by
Scaling Knowledge Graph Architectures with AIScaling Knowledge Graph Architectures with AI
Scaling Knowledge Graph Architectures with AIEnterprise Knowledge
30 views15 slides
Vertical User Stories by
Vertical User StoriesVertical User Stories
Vertical User StoriesMoisés Armani Ramírez
14 views16 slides
Democratising digital commerce in India-Report by
Democratising digital commerce in India-ReportDemocratising digital commerce in India-Report
Democratising digital commerce in India-ReportKapil Khandelwal (KK)
15 views161 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...James Anderson
85 views32 slides

Recently uploaded(20)

Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2217 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson85 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi127 views
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada136 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10248 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
Serverless computing with Google Cloud (2023-24) by wesley chun
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)
wesley chun11 views
Attacking IoT Devices from a Web Perspective - Linux Day by Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri16 views

OOP Is More Than Cars and Dogs

  • 1. OOP is More Than Cars and Dogs Chris Tankersley php[tek] 2015 php[tek] 2015 1
  • 2. Who Am I • PHP Programmer for over 10 years • Work/know a lot of different languages, even COBOL • Primarily do Zend Framework 2 • https://github.com/dragonmantank php[tek] 2015 2
  • 3. Quick Vocabulary Lesson • Class – Definition of code • Object – Instantiation of a Class • Member – Variable belonging to a class • Method – Function belonging to a class There will be more as we go along php[tek] 2015 3
  • 4. php[tek] 2015 4 Class class Employee { protected $name; // This is a member protected $number; // This is a Method public function setData($data) { $this->name = $data['name']; $this->number = $data['number']; } public function viewData() { echo <<<ENDTEXT Name: {$this->name} Number: {$this->number} ENDTEXT; } }
  • 5. Object <?php $manager= new Manager(); // ^ // | // `--- This is the Object php[tek] 2015 5
  • 6. Why are we using OOP? php[tek] 2015 6
  • 7. Let’s count the reasons • Because we’re told to, procedural programming leads to spaghetti code • We deal with objects every day, so it shouldn’t be too hard • We want to allow for code re-use • We want to group like code together • We want to easily extend our code • We want to be able to easily test our code php[tek] 2015 7
  • 8. Getting OOP Right is Complicated php[tek] 2015 8
  • 15. Can a Dog have Wheels? • Discuss (or listen to me talk some more) php[tek] 2015 15
  • 17. What we’re all taught • Classes are “things” in the real world • We should construct class members based on Attributes • Number of wheels • Sound it makes • We should construct class methods based on “Actions” • Running • Speaking • Jumping php[tek] 2015 17
  • 18. New Vocabulary • Parent Class – Class that is extended • Child Class – Class that is extending another class In PHP, a class can be both a Child and a Parent at the same time php[tek] 2015 18
  • 19. Where I Learned It php[tek] 2015 19
  • 20. Our Structure php[tek] 2015 20 Employee Manager Scientist Laborer
  • 21. The Employee Class php[tek] 2015 21 abstract class Employee { protected $name; // Employee Name protected $number; // Employee Number public function setData($data) { $this->name = $data['name']; $this->number = $data['number']; } public function viewData() { echo <<<ENDTEXT Name: {$this->name} Number: {$this->number} ENDTEXT; } }
  • 22. The Manager Class php[tek] 2015 22 class Manager extends Employee { protected $title; // Employee Title protected $dues; // Golf Dues public function setData($data) { parent::setData($data); $this->title = $data['title']; $this->dues = $data['dues']; } public function viewData() { parent::viewData(); echo <<<ENDTEXT Title: {$this->title} Golf Dues: {$this->dues} ENDTEXT; } }
  • 23. The Scientist Class php[tek] 2015 23 class Scientist extends Employee { protected $pubs; // Number of Publications public function setData($data) { parent::setData($data); $this->pubs = $data['pubs']; } public function viewData() { parent::viewData(); echo <<<ENDTEXT Publications: {$this->pubs} ENDTEXT; } }
  • 24. The Laborer Class php[tek] 2015 24 class Laborer extends Employee { }
  • 25. What does this teach us? • Inheritance • Makes it easier to group code together and share it amongst classes • Allows us to extend code as needed • PHP allows Single inheritance php[tek] 2015 25
  • 26. We use it all the time namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; Class IndexController extends AbstractActionController { public function indexAction() { /** @var VendorVendorService $vendor */ $vendor = $this->serviceLocator->get('VendorVendorService'); $view = new ViewModel(); return $view; } } php[tek] 2015 26
  • 27. Why it Works (Most of the time, Kinda) • Allows us to extend things we didn’t necessarily create • Encourages code re-use • Allows developers to abstract away things php[tek] 2015 27
  • 28. How to use it • Understand the difference between Public, Protected, and Private • Public – Anyone can use this, even children • Protected – Anything internal can use this, even children • Private – This is mine, hands off • Abstract vs Concrete Classes • Abstract classes cannot be instantiated directly, they must be extended php[tek] 2015 28
  • 29. The Employee Class php[tek] 2015 29 abstract class Employee { protected $name; // Employee Name protected $number; // Employee Number public function setData($data) { $this->name = $data['name']; $this->number = $data['number']; } public function viewData() { echo <<<ENDTEXT Name: {$this->name} Number: {$this->number} ENDTEXT; } }
  • 30. The Manager Class php[tek] 2015 30 class Manager extends Employee { protected $title; // Employee Title protected $dues; // Golf Dues public function setData($data) { parent::setData($data); $this->title = $data['title']; $this->dues = $data['dues']; } public function viewData() { parent::viewData(); echo <<<ENDTEXT Title: {$this->title} Golf Dues: {$this->dues} ENDTEXT; } }
  • 31. An Example // Fatal error: Cannot instantiate abstract class Employee $employee = new Employee(); // We can do this though! $manager = new Manager(); // Fatal error: Cannot access protected property Manager::$name $manager->name = 'Bob McManager’; // setData is public, so we can use that $manager->setData(['name' => 'Bob McManager’,'number' => 1]); // We can also view the data, since it's public $manager->viewData(); php[tek] 2015 31
  • 32. Why can Inheritance Be Bad • PHP only allows Single Inheritance on an Class • You can have a series of Inheritance though, for example CEO extends Manager, Manager extends Employee • Long inheritance chains can be a code smell • Private members and methods cannot be used by Child classes • Single Inheritance can make it hard to ‘bolt on’ new functionality between disparate classes php[tek] 2015 32
  • 34. The General Idea • Classes contain other classes to do work and extend that way, instead of through Inheritance • Interfaces define “contracts” that objects will adhere to • Your classes implement interfaces to add needed functionality php[tek] 2015 34
  • 35. Interfaces interface EmployeeInterface { protected $name; protected $number; public function getName(); public function setName($name); public function getNumber(); public function setNumber($number); } interface ManagerInterface { protected $golfHandicap; public function getHandicap(); public function setHandicap($handicap); } php[tek] 2015 35
  • 36. Interface Implementation class Employee implements EmployeeInterface { public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } } class Manager implements EmployeeInterface, ManagerInterface { // defines the employee getters/setters as well public function getHandicap() { return $this->handicap; } public function setHandicap($handicap) { $this->handicap = $handicap; } } php[tek] 2015 36
  • 37. This is Good and Bad • “HAS-A” is tends to be more flexible than “IS-A” • Somewhat easier to understand, since there isn’t a hierarchy you have to backtrack • Each class must provide their own Implementation, so can lead to code duplication php[tek] 2015 37
  • 38. Traits • Allows small blocks of code to be defined that can be used by many classes • Useful when abstract classes/inheritance would be cumbersome • My Posts and Pages classes shouldn’t need to extend a Slugger class just to generate slugs. php[tek] 2015 38
  • 39. Avoid Code-Duplication with Traits trait EmployeeTrait { public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } } class Employee implements EmployeeInterface { use EmployeeTrait; } class Manager implements EmployeeInterface, ManagerInterface { use EmployeeTrait; use ManagerTrait; } php[tek] 2015 39
  • 40. Taking Advantage of OOP php[tek] 2015 40
  • 42. What is Coupling? • Coupling is how dependent your code is on another class • The more classes you are coupled to, the more changes affect your class php[tek] 2015 42
  • 43. namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class MapController extends AbstractActionController { public function indexAction() { // Position is an array with a Latitude and Longitude object $position = $this->getServiceLocator()->get('MapService’) ->getLatLong('123 Main Street', 'Defiance', 'OH'); echo $position->latitude->getPoint(); } } php[tek] 2015 43
  • 46. What is Dependency Injection? • Injecting dependencies into classes, instead of having the class create it • Allows for much easier testing • Allows for a much easier time swapping out code • Reduces the coupling that happens between classes php[tek] 2015 46
  • 47. Method Injection class MapService { public function getLatLong(GoogleMaps $map, $street, $city, $state) { return $map->getLatLong($street . ' ' . $city . ' ' . $state); } public function getAddress(GoogleMaps $map, $lat, $long) { return $map->getAddress($lat, $long); } } php[tek] 2015 47
  • 48. Constructor Injection class MapService { protected $map; public function __construct(GoogleMaps $map) { $this->map = $map; } public function getLatLong($street, $city, $state) { return $this ->map ->getLatLong($street . ' ' . $city . ' ' . $state); } } php[tek] 2015 48
  • 49. Setter Injection class MapService { protected $map; public function setMap(GoogleMaps $map) { $this->map = $map; } public function getMap() { return $this->map; } public function getLatLong($street, $city, $state) { return $this->getMap()->getLatLong($street . ' ' . $city . ' ' . $state); } } php[tek] 2015 49
  • 51. Single Responsibility Principle • Every class should have a single responsibility, and that responsibility should be encapsulated in that class php[tek] 2015 51
  • 52. What is a Responsibility? • Responsibility is a “Reason To Change” – Robert C. Martin • By having more than one “Reason to Change”, code is harder to maintain and becomes coupled • Since the class is coupled to multiple responsibilities, it becomes harder for the class to adapt to any one responsibility php[tek] 2015 52
  • 53. An Example /** * Create a new invoice instance. * * @param LaravelCashierContractsBillable $billable * @param object * @return void */ public function __construct(BillableContract $billable, $invoice) { $this->billable = $billable; $this->files = new Filesystem; $this->stripeInvoice = $invoice; } /** * Create an invoice download response. * * @param array $data * @param string $storagePath * @return SymfonyComponentHttpFoundationResponse */ public function download(array $data, $storagePath = null) { $filename = $this->getDownloadFilename($data['product']); $document = $this->writeInvoice($data, $storagePath); $response = new Response($this->files->get($document), 200, [ 'Content-Description' => 'File Transfer', 'Content-Disposition' => 'attachment; filename="'.$filename.'"', 'Content-Transfer-Encoding' => 'binary', 'Content-Type' => 'application/pdf', ]); $this->files->delete($document); return $response; } php[tek] 2015 53 https://github.com/laravel/cashier/blob/master/src/Laravel/Cashier/Invoice.php
  • 54. Why is this Bad? • This single class has the following responsibilities: • Generating totals for the invoice (including discounts/coupons) • Generating an HTML View of the invoice (Invoice::view()) • Generating a PDF download of the invoice(Invoice::download()) • This is coupled to a shell script as well • Two different displays handled by the class. Adding more means more responsibility • Coupled to a specific HTML template, the filesystem, the Laravel Views system, and PhantomJS via the shell script php[tek] 2015 54
  • 55. How to Improve • Change responsibility to just building the invoice data • Move the ‘output’ stuff to other classes php[tek] 2015 55
  • 57. [Could not afford licensing fee for Grumpy Testing Picture] php[tek] 2015 57
  • 58. This is not a testing talk • Using Interfaces makes it easier to mock objects • Reducing coupling and following Demeter’s Law makes you have to mock less objects • Dependency Injection means you only mock what you need for that test • Single Responsibility means your test should be short and sweet • Easier testing leads to more testing php[tek] 2015 58
  • 60. We can make a dog with wheels! • Abstract class for Animal • Class for Dog that extends Animal • Trait for Wheels • With the write methodology, we could even unit test this In the real world, we can now represent a crippled dog php[tek] 2015 60
  • 61. Here’s a cute dog instead php[tek] 2015 61
  • 63. Photos • Slide 9 - http://bit.ly/1dkaoxS • Slide 10 - http://bit.ly/1c4Gc8z • Slide 11 - http://bit.ly/1R3isBp • Slide 12 - http://bit.ly/1ScEWRZ • Slide 13 - http://bit.ly/1Bc0qUv • Slide 14 - http://bit.ly/1ILhfNV php[tek] 2015 63