Advertisement

Advanced PHP Simplified - Sunshine PHP 2018

Senior Software Engineer PHP at Nucleus Security
Feb. 9, 2018
Advertisement

More Related Content

Advertisement
Advertisement

Advanced PHP Simplified - Sunshine PHP 2018

  1. Advanced PHP Simplified Mark Niebergall https://joind.in/talk/8887c
  2. About Mark Niebergall ● PHP since 2005 ● Masters degree in MIS ● Senior Software Engineer ● Drug screening project ● UPHPU President, Speaker ● CSSLP, SSCP Certified and SME ● Drones, fishing, skiing, father, husband
  3. Advanced PHP Simplified
  4. Advanced PHP Simplified
  5. Disclaimer ● Breadth not depth ● Think about your current coding style and architecture ● Leverage topics covered ● Ask questions along the way
  6. Objective ● Discuss some advanced PHP concepts ● Cover technical implementation ● Understand when and how to use features ○ Code during the talk
  7. Topics to Cover ● Abstract ● Interface ● Trait ● Namespace ● Dependency Injection
  8. Abstract
  9. Abstract ● Abstract Art ● Abstract of text ● Abstract thought or idea
  10. Abstract Class ● abstract class X { abstract public function doSomething(); } ● class Y extends X { public function doSomething() {...} }
  11. Abstract Class ● abstract public function doSomething($a); ● protected function somethingElse() {...}
  12. Abstract Class ● Implemented abstract method signatures must match ○ Visibility modifier ○ Name ○ Parameters ○ Return type
  13. Abstract Class ● Can have methods with functionality ● Can have class properties ● Can have class constants ● Can extend one abstract class ○ Can have multiple levels ● Cannot be instantiated
  14. Abstract Uses ● X "is a" Y (NOT "has a")
  15. Abstract Uses ● Represents an idea or base concept ● Composition over Inheritance ● Centralizing logic ● Reducing duplicate code ● Avoid a maze - keep code readable
  16. Abstract Examples ● Truck extends Vehicle ● Laptop extends Computer ● Email extends Communication
  17. Abstract Examples ● abstract class Animal ● abstract class Mammal extends Animal ● abstract class Canine extends Mammal ● abstract class Dog extends Canine ● class GermanSheperd extends Dog
  18. abstract class Animal { abstract public function breathe(Lungs $lungs) : Lungs; protected function beAlive() : Animal {…} } abstract class Mammal extends Animal { protected function warmBlood(Blood $blood) : Blood {...} abstract public function growHair(); } abstract class Canine extends Mammal { abstract public function wagTail(Tail $tail); } abstract class Dog extends Canine { abstract protected function bark(); } class GermanSheperd extends Dog {...}
  19. abstract class Pen { protected $length; abstract public function usePen(); abstract public function refuel(); protected function setLength($length) { $this->length = (float) $length; return $this; } public function getLength() { return $this->length; } }
  20. abstract class Bird { protected $beak; abstract public function walk(); abstract private function eat(); protected function fly(Wings $wings) { $wings->flap(); } } class Flamingo extends Bird { public function walk() {...} private function eat() {...} }
  21. Abstract
  22. Interface
  23. Interface ● User Interface ● System Interface ● Provides a way for communication or control ● Connect two things together
  24. Interface ● interface X { public function doStuff(Thing $thing); public function other() : Thing; } ● class Y implements X {...} ● abstract Z implements V, W, X {...}
  25. Interface ● Methods must be implemented ● Method signatures must match ● Methods are left empty in the interface
  26. Interface Uses ● When no logic is required but method signatures can be reused ● Contract between concept and implementation
  27. Interface Uses ● Class can implement multiple interfaces ● Leaves implementation to be handled in the class ● Can be used with abstract and class ● Cannot be used with a trait
  28. Interface Uses ● All methods must be public ● No properties allowed ● Can have public class constants
  29. Interface Examples ● Auditing ● Sea Creatures (mammal, fish, etc) ● USB
  30. Interface Examples ● Authentication methods ● Responses to a request ● Orders from vendors and customers
  31. interface LightInterface { const LIGHT_SPEED = 299792458; public function shine(Energy $energy) : Light; public function travel(float $x, float $y, float $z); }
  32. interface ProcessSomething { public function process(Something $something); }
  33. Interface
  34. Traits
  35. Traits ● Characteristics of something ● Attributes possessed
  36. Trait ● trait X { public $property; protected function doStuff() {...} } ● class Something { use X; }
  37. Trait ● PHP 5.4+ ● Can have methods and properties ● "Looks" like a concrete class ● Horizontal Inheritance ● Cannot be instantiated
  38. Trait ● Promotes code reuse ● Unrestricted by inheritance hierarchies ● Pulls together grouped functionality ● Multiple traits allowed
  39. Trait ● Used alongside abstracts and interfaces ● Used in abstract, concrete class, and trait ● Cannot implement an interface ● Cannot extend a class ● Cannot have class constants
  40. Trait ● Awareness concept ○ ContainerAware ○ AuditAware ○ AdapterAware
  41. Trait ● Naming collisions ○ First the current class ○ Then the trait ○ Last the parent class
  42. Trait ● Fatal error if trait method collisions are not resolved ● ‘insteadof’ for one, ‘as’ for multiples
  43. abstract class TheAbstract { public function hello() { echo ‘Hello from the abstract.’; } } trait TheTrait { public function hello() { echo ‘Hello from the trait.’; } } class TheClass extends TheAbstract { use TheTrait; public function hello() { echo ‘Hello from the class.’; } }
  44. abstract class TheAbstract { public function hello() { echo ‘Hello from the abstract.’; } } trait TheTrait { public function hello() { echo ‘Hello from the trait.’; } } class TheClass extends TheAbstract { use TheTrait { TheTrait insteadof TheAbstract; } public function hello() { echo ‘Hello from the class.’; } public function helloAbstract() { parent::hello(); } }
  45. abstract class TheAbstract { public function hello() { echo ‘Hello from the abstract.’; } } trait TheTrait { public function hello() { echo ‘Hello from the trait.’; } } class TheClass extends TheAbstract { use TheTrait { TheTrait::hello as helloTrait; } public function hello() { echo ‘Hello from the class.’; } public function helloAbstract() { parent::hello(); } }
  46. Trait ● Property collisions ○ Same visibility and initial value
  47. Trait ● Can change visibility modifier ○ use TheTrait { TheTrait::hello as protected; }
  48. Trait ● Can have abstract methods ○ Not recommended
  49. Trait ● Can have static methods ○ trait TheTrait { public static function thing() {...} }
  50. Trait Usage ● Common attributes and functionality ● Consider: required for functionality within this class?
  51. Trait Usage ● Keep vertical inheritance in mind, especially when making changes ● Reduces some limitations of single inheritance
  52. Trait Examples ● Car tire ● Sea creature
  53. trait Circular { protected $radius; public function getDiameter() { return bcmul($this->radius, 2); } public function getArea() { return bcmul(pi(), bcpow($this->radius, 2)); } } class Pie { use Circular; } class Tire { use Circular; }
  54. trait Wave { protected $length; protected $amplitude; protected $frequency; public function setLength($length) { $this->length = (float) $length; return $this; } public function getLength() { return $this->length; } public function setAmplitude($amplitude) { $this->amplitude = (float) $amplitude; return $this; } public function getAmplitude() { return $this->amplitude; } }
  55. Trait
  56. Namespaces
  57. Namespaces ● Container for identification ● Encapsulate items
  58. Namespace ● namespace CompanyDomainTopicSubgroup; use OtherAreaZ; class A { protected function doStuff() { $z = new Z; } }
  59. Namespace ● PHP 5.3+ ● Grouping related classes together
  60. Namespace Uses ● Shorten_Up_Really_Long_Class_Names_ In_Your_Application ● Avoid naming collisions
  61. Namespace Uses ● Autoloader with file structure built around namespaces ○ Can have multiple ○ Often one for composer, one for project
  62. Namespace Uses class Autoloader { public static function registerAutoloader() { spl_autoload_register(array('self', 'loader'), false); } public static function loader($className) { require __DIR__ . ‘/../../’ . $className . ‘.php’; } } require_once __DIR__ . ‘/../vendor/autoload.php’; Autoloader::registerAutoloader();
  63. Namespace Uses ● Must be first code in file ● Aliasing: use WidgetXyz as X;
  64. Namespace Uses ● Watch out for keywords ○ Trait ○ Case ○ Switch ○ Int ○ Bool
  65. Namespace Uses ● Avoid collisions ○ use BobCat as BobCat; ○ use JaneCat as JaneCat;
  66. Namespace Examples ● Last name ○ namespace Smith; ○ class John {...}
  67. Namespace Examples ● Just_About_Any_Long_Name ○ namespace JustAboutAnyLong; ○ class Name {...}
  68. Namespace Examples Domain/Subject/Science.php: <?php namespace DomainSubject; use OtherDomainSubjectThing; use OtherDomainArea; class Science { protected function doSomething(Thing $thing) { $thing->doWhatItDoes(); } public function otherStuff(AreaNorth $north) { $north->head(AreaSouth::getPole()); } }
  69. Namespace
  70. Dependency Injection ● Send object dependencies into an object from outside ● Pass class as parameter into a method rather than method building the class
  71. Dependency Injection Uses ● Constructor: __construct(X $x, ...) ● Setter: setX(X $x) { $this->x = $x; } ● Interface: setX(X $x); ● Method: doSomething(Thing $thing) {...}
  72. Dependency Injection ● Big help for unit tests ● Allows for use of mock objects ● See PHPUnit documentation for getMockBuilder, getMockForAbstractClass, and other PHPUnit methods
  73. Dependency Injection ● Does add more lines of code ● Composition over Inheritance
  74. Dependency Injection Uses ● Service locator ● Factories
  75. Dependency Injection Examples ● Desktop computer parts from different manufacturers ● Lamp light bulbs: colors, types
  76. namespace Pen; use LightLight as LightLaser; require_once __DIR__ . '/../Autoloader.php'; Autoloader::registerAutoloader(); class Laser extends Pen { protected $lightLaser; public function __construct(LightLaser $lightLaser = null) { $this->lightLaser = $lightLaser; } protected function getLightLaser() { if (is_null($this->lightLaser)) { $this->lightLaser = new LightLaser; } return $this->lightLaser; } public function usePen() { $this->getLightLaser()->shine(); } public function refuel() { $this->getLightLaser()->replaceBatteries(); } }
  77. Dependency Injection
  78. Things to Consider ● Open group discussion
  79. Things to Consider ● Why need for abstract vs interface vs trait? ● Benefits of vertical vs horizontal inheritance?
  80. Things to Consider ● Traits vs dependency injection? ● Tradeoffs of complexity vs code reuse (think of database normalization)
  81. Things to Consider ● Implementation considerations ● Code consolidation
  82. Conclusion ● Goals for using concepts ● Evaluate current architectural approach ● Just scratched the surface on topics covered ● Consider how concepts all come together for solution
  83. Questions? ● https://joind.in/talk/8887c
Advertisement