3. What makes good software?
"The function of good software is to make the complex
appear to be simple." - Grady Booch
"Always code as if the guy who ends up maintaining your
code will be a violent psychopath who knows where you
live." - Martin Golding
Good software needs good software engineering
5. What is software engineering then?
Software engineering is the application of a systematic,
quantiïŹable, disciplined approach to development.
Programming is simply one phase of development
6. PHP & Software Engineering
PHP is quick to learn, almost to a fault
Easy to write bad code
However, PHP provides tools to facilitate the creation of
solid and organized software
PHP started as a procedural language, but has evolved!
8. Whatâs Wrong With That!?
Nothing is really wrong with it. But...
Itâs really hard to read and follow
As the code base grows, maintainability decreases
New additions often become hacks
Designers canât easily design unless they know PHP
9. How else would I do it?!
Object Oriented Programming FTW!
10. What is OOP?
Programming paradigm using âobjectsâ and their interactions
Not really popular until 1990âs
Basically the opposite of procedural programming
11. When would I use this OOP stuff?
When you...
ïŹnd yourself repeating code
want to group certain functions together
want to easily share some of your code
want to have an organized code base
think you may reuse some of your code later
13. OOP Techniques
Before we get to the code, a little OOP primer
Encapsulation
Modularity
Inheritance
Polymorphism
14. Encapsulation (Itâs like a Twinkie!)
Group together data and functionality (bananas and cream)
Hide implementation details (how they get the ïŹlling in there)
Provide an explicitly deïŹned
way to interact with the data
(theyâre always the same shape)
Hides the creamy center!
15. Modularity (Itâs like this sofa!)
A property of an application that measures the extent to
which the application has been composed of separate parts
(modules)
Easier to have a more
loosely-coupled application
No one part is programatically
bound to another
16. Inheritance (Itâs like Joan & Melissa Rivers)
A hierarchical way to organize data and functionality
Children receive functionality and properties of their
ancestors
is-a and has-a relationships
Inherently (hah!) encourages
code reuse
17. Polymorphism (Itâs like that guy)
Combines all the other techniques
Kind of complicated so weâll get to
it later
18. Need to know terms
class - A collection of interrelated functions and variables
that manipulates a single idea or concept.
instantiate - To allocate memory for a class.
object - An instance of a class
method - A function within a class
class member - A method or variable within a class
19. What does a class look like?
<?php
// this is a class. $name and getHeight() are class members
class Person
{
public $name = âBob McSmithyPantsâ; // this is a class variable
public function getHeight() // this is a class method
{}
}
?>
20. How to instantiate a class
<?php
$p = new Person(); // at this point $p is a new Person object
?>
Now anyone can use the Person object (call its methods,
change its variables, etc.)
24. Public
Anyone (the class itself or any instantiation of that class) can have access to the
method or property
If not speciïŹed, a method or property is declared public by default
25. Public Example
<?php
class Person
{
public function getName()
{
return âBob McSmithyPantsâ;
}
}
?>
<?php
$p = new Person();
echo $p->getName();
?>
27. Private Example
<?php
class Person
{
public function firstName()
{
return âBobâ;
}
private function lastName()
{
return âMcSmithyPantsâ;
}
}
?>
<?php
$p = new Person();
echo $p->firstName(); // this will work
echo $p->lastName(); // this does not work
?>
28. Protected
Only the class itself or a class that extends this class can
have access to the method or property
29. Protected Example
<?php
class Person
{
protected function getName()
{
return âBob McSmithyPantsâ;
}
}
class Bob extends Person
{
public function whatIsMyName()
{
return $this->getName();
}
}
?>
<?php
$p = new Person();
echo $p->getName(); // this wonât work
$b = new Bob();
echo $b->whatIsMyName(); // this will work
?>
30. What was with that $this stuff?
You can access the protected data and methods with âobject
accessorsâ
These allow you to keep the bad guys out, but still let the good
guys in.
32. $this
variable
refers to the current instantiation
<?php
class Person
{
public $name = âbobâ;
public function getName()
{
return $this->name;
}
}
$p = new Person();
echo $p->getName();
// will print bob
?>
33. self
keyword that refers to the class itself regardless of
instantiation status
not a variable
<?php
class Person
{
public static $name = âbobâ;
public function getName()
{
return self::$name;
}
}
$p = new Person();
echo $p->getName();
// will print bob
?>
34. parent
<?php
class Person keyword that refers to the parent class
{
public $name = âbobâ;
most often used when overriding
public function getName()
{ methods
return $this->name;
}
} also not a variable!
class Bob extends Person
{ What would happen if we used
public function getName()
{ $this->getName() instead of
}
return strtoupper(parent::getName()); parent::getName()?
}
$bob = new Bob();
echo $bob->getName();
// will print BOB
?>
35. Class constants
DeïŹned with the âconstâ keyword
Always static
Not declared or used with $
Must be a constant expression, not a variable, class member,
result of a mathematical expression or a function call
Must start with a letter
36. Constant Example
<?php
class DanielFaraday
{
const MY_CONSTANT = 'Desmond';
public static function getMyConstant()
{
return self::MY_CONSTANT;
}
}
echo DanielFaraday::MY_CONSTANT;
echo DanielFaraday::getMyConstant();
$crazyTimeTravelDude = new DanielFaraday();
echo $crazyTimeTravelDude->getMyConstant();
?>
37. Class and Method Properties
Final and Static
Classes and methods can be declared either ïŹnal, static, or
both!
38. Important Note!
Class member scopes (public, private, and protected) and
the class and method properties (ïŹnal and static) are not
mutually exclusive!
40. Final Example
<?php
class Person
{
public final function getName()
{
return âSteve Daveâ;
}
}
class Bob extends Person
{
public function getName()
{
return âBob McSmithyPantsâ;
}
}
// this will fail when trying to include Bob
?>
41. Static
A method declared as static can be accessed without
instantiating the class
You cannot use $this within static functions because $this
refers to the current instantiation
Accessed via the scope resolution operator ( :: )
i.e. â About::getVersion();
42. Static Example
<?php
class About
{
public static function getVersion()
{
return âVersion 2.0â;
}
}
?>
<?php echo About::getVersion(); ?>
44. Abstract Classes
Never directly instantiated
Any subclass will have the properties and methods of the
abstract class
Useful for grouping generic functionality of subclassed
objects
At least one method must be declared as abstract
45. Abstract Example
<?php
<?php
abstract class Car
{ $honda = new Honda();
private $_color; $honda->setColor(âblackâ);
$honda->drive();
abstract public function drive();
?>
public function setColor($color)
{
$this->_color = $color;
}
public function getColor()
{
return $this->_color;
}
}
class Honda extends Car
{
public function drive()
{
$color = $this->getColor();
echo âIâm driving a $color car!â;
}
}
?>
46. Interfaces
DeïŹnes which methods are required for implementing an
object
SpeciïŹes the abstract intention of a class without providing
any implementation
Like a blueprint or template
A class can simultaneously implement multiple interfaces
47. Interface Example
<?php
<?php
interface Car
{ $honda = new Honda();
public function start(); $honda->start();
public function drive(); $honda->drive();
public function stop(); $honda->stop();
} ?>
class Honda implements Car
{
public function start()
{
echo âCar is started!â;
}
public function drive()
{
echo âIâm driving!â;
}
public function stop()
{
echo âThe car has stopped!â;
}
}
?>
48. instanceof
Operator to check if one class is an instance of another class
<?php
<?php
class Car
class Car
{}
{}
class Honda extends Car
class Honda extends Car
{}
{}
$car = new Car(); OR $car = new Honda();
$honda = new Honda();
if ($car instanceof Car) {
if ($car instanceof $honda) {
echo âtrueâ;
echo âtrueâ;
} else {
} else {
echo âfalseâ;
echo âfalseâ;
}
}
?>
?>
What will get printed?
49. Type Hinting
PHP is not strongly typed (i.e. - variables can be
pretty much anything anytime)
In PHP4 you have to do a lot of checking
to ïŹnd out if a parameter is the correct type
Type Hinting helps make this more efïŹcient
50. Type Hinting Example
<?php
// this can be made better with type hinting!
public function promoteToManager($bob)
{
if (!is_a($bob, âPersonâ)) {
throw new Exception(â$bob is not a Person!â);
}
// do stuff with $bob
}
?>
... becomes ...
<?php
// this is better!
public function promoteToManager(Person $bob)
{
// do stuff with $bob
}
?>
51. A Few More Terms
serialize - Converting an object to a binary form (i.e. -
writing an object to a ïŹle)
unserialize - The opposite of serialize. To convert the
stored binary representation of an object back into the
object.
reference - An pointer to an objectâs location in memory
rather than the actual object
52. Magic Methods
Methods provided by PHP5 automagically (called by PHP on certain events)
Always begin with __ (two underscores)
Declared public by default but can be overridden
54. __construct() & __destruct()
__construct() runs when a new object is instantiated.
Suitable for any initialization that the object may need before
itâs used.
__destruct() runs when all references to an object are no
longer needed or when the object is explicitly destroyed.
55. __get()
__get() is called when trying to access an undeclared
property
<?php
class Car
{
protected $_data = array(
âdoorâ => 4,
âtypeâ => âJeepâ,
âvinâ => â2948ABJDKZLEâ
);
public function __get($varName)
{
return $this->_data[$varName];
}
}
$car = new Car();
echo $car->vin; // will print out 2948ABJDKZLE
?>
56. __set()
__set() is called when trying to assign an undeclared
property
<?php
class Car
{
protected $_data = array(
âdoorâ => 4,
âtypeâ => âJeepâ,
âvinâ => â2948ABJDKZLEâ
);
public function __set($varName, $value)
{
$this->_data[$varName] = $value;
}
}
$car = new Car();
$car->vin = âABCâ;
echo $car->vin; // will print out ABC
?>
57. __isset()
Used to check whether or not a data member has been declared
<?php
class Car
{
protected $_data = array(
âdoorâ => 4,
âtypeâ => âJeepâ,
âvinâ => â2948ABJDKZLEâ
);
public function __isset($varName)
{
return isset($this->_data[$varName]);
}
}
$car = new Car();
if (isset($car->color)) {
echo âcolor is set!â;
} else {
echo âcolor isnât set!â;
}
// will print color isnât set
?>
58. __unset()
Removes a data member from a class
<?php
class Car
{
protected $_data = array(
âdoorâ => 4,
âtypeâ => âJeepâ,
âvinâ => â2948ABJDKZLEâ
);
public function __unset($varName)
{
return unset($this->_data[$varName]);
}
}
$car = new Car();
unset($car->vin);
if (isset($car->vin)) {
echo âvin is set!â;
} else {
echo âvin isnât set!â;
}
// will print vin isnât set
?>
59. __call()
__call() is executed when trying to access a method that
doesnât exist
This allows you to handle unknown functions however youâd
like.
60. _call() Example
<?php
class Sample
{
public function __call($func, $arguments)
{
echo "Error accessing undefined Method<br />";
echo "Method Called: " . $func . "<br />";
echo "Argument passed to the Method: ";
print_r($arguments);
}
}
$sample = new Sample();
echo $sample->doSomeStuff("Test");
?>
61. __toString()
Returns the string representation of a class
Is automatically called whenever trying to print or echo a
class.
Useful for deïŹning exactly what you want an object to look
like as a string
Can also be used to prevent people from printing the class
without throwing an exception
62. __toString() Example
<?php
class SqlQuery
{
protected $_table;
protected $_where;
protected $_orderBy;
protected $_limit;
public function __construct($table, $where, $orderBy, $limit)
{
$this->_table = $table;
$this->_where = $where;
$this->_orderBy = $orderBy;
$this->_limit = $limit;
}
public function __toString()
{
$query = âSELECT * â
. âFROM $this->_table â
. âWHERE $this->_where â
. âORDER BY $this->_orderBy â
. âLIMIT $this->_limitâ;
return $query;
}
}
$test = new SqlQuery('tbl_users', âuserType = âadminââ, ânameâ, 10);
echo $test;
?>
63. __sleep()
Called while serializing an object
__sleep() lets you deïŹne how you want the object to be
stored
Also allows you to do any clean up you want before
serialization
Used in conjunction with __wakeup()
64. __wakeup()
The opposite of __sleep() basically
Called when an object is being unserialized
Allows you to restore the class data to its normal form
65. __clone()
In php setting one object to another
does not copy the original object;
only a reference to the original is
made
To actually get a second copy of the
object, you must use the __clone
method
66. __clone() example
<?php
class Animal
{
public $color;
public function setColor($color)
{
$this->color = $color;
}
public function __clone()
{
echo "<br />Cloning animal...";
}
}
$tiger = new Animal();
$tiger->color = "Orange";
$unicorn = clone $tiger;
$unicorn->color = "white";
echo "<br /> A tiger is " . $tiger->color;
echo "<br /> A unicorn is " . $unicorn->color;
?>
67. __autoload()
Called when you try to load a class in a ïŹle that was not
already included
Allows you to do new myClass() without having to include
myClass.php ïŹrst.
68. _autoload() example
<?php
class Account
{
public function __autoload($classname)
{
require_once $classname . â.phpâ; //$classname will be Profile
}
public function __construct()
{
$profile = new Profile();
}
}
?>
69. A little example
You can use all this stuff you just learned about inheritance,
scoping, interfaces, and abstract classes to do some more
complex things!
70. How Would You Solve This?
I have a bunch of shapes of which I want to ïŹnd the area
I could get any combination of different shapes
I want to be able to ïŹnd the area without having to know
the details of the calculation myself.
What OOP techniques could we use to solve this problem?
72. Polymorphism
The last object-oriented technique!
Combination of the other techniques
Allowing values of different types to be handled by a uniform
interface
75. Polymorphism
<?php
abstract class Shape
{
private $_color;
public function __construct($color)
{
$this->_color = $color;
}
public function getColor()
{
return $this->_color;
}
}
?>
76. Polymorphism
<?php
class Rectangle extends Shape implements HasArea
{
private $_w; // width
private $_h; // height
public function __construct($color, $w, $h)
{
parent::__construct($color);
$this->_w = $w;
$this->_h = $h;
}
public function area()
{
return ($this->_w * $this->_h);
}
}
?>
77. Polymorphism
<?php
class Circle extends Shape implements HasArea
{
private $_r; // radius
public function __construct($color, $r)
{
parent::__construct($color);
$this->_r = $r;
}
public function area()
{
return (3.14 * pow($this->_r, 2));
}
}
?>
78. Polymorphism
<?php
// this function will only take a shape that implements HasArea
function getArea(HasArea $shape)
{
return $shape->area();
}
$shapes = array(
'rectangle' => new Rectangle("red", 2, 3),
'circle' => new Circle("orange", 4)
);
foreach ($shapes as $shapeName => $shape) {
$area = getArea($shape);
echo $shapeName . " has an area of " . $area . "<br />";
}
// will print:
// rectangle has an area of 6
// circle has an area of 50.24
?>
79. QUESTIONS?
Jason Austin
@jason_austin
jfaustin@gmail.com
http://jasonawesome.com
Notas do Editor
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
Describe a little about how exactly a class becomes an object and how that works with respect to interacting with an object in memory and not the class specifically\n