Object Oriented Programming with PHP Training Notes
Object Oriented Programming with PHP Training Notes

Object Oriented Programming Theory and Methodologies

  • What is an object
    • PHP Primitives are basic types of data that are proved by programming language
      • booleans – true/false
      • floating-point number – fractional value
      • integers – whole numbers, can be negative
      • string – string of characters
    • Objects are complex data structures that haves
      • attributes
      • behaviors
    • Objects can have multiple data types each with their own values, primitives only one data type and value
      • ex. – String: toronto

        Object: street number: 55, city: Toronto, subdivision: Ontario

        • each value in object is called property
  • Class
    • a class is a blueprint that defines attributes and behaviors that make up an object
    • objects are instances of a class
      • each occurrence of an object of a class has all attributes and behaviors for class
        • individual attributes will be same, but content can differ
    • classes modularize program function
      • separate distinct features with little overlap
      • ex. – class:address

        attributes: city, subdivision, postal code

        behavior: postal code lookup

        • this means any object of class:address will have same attributes and behavior
  • Why OOP?
    • Allows you to organize large project into manageable pieces
    • by contrast, procedural programming is a set of instructions that the computer must follow step-by-step
      • linear
      • nothing wrong inherently, problem comes when scaling up project size
    • OOP introduces struction and principles aimed at mitigating scaling issues
      • features include
        • abstraction
          • defines data and program structures using representation of meaning, while hiding implementation
            • allows human-readable terminology to be used as part of software solution
        • encapsulation
          • exposes functionality while restricting access to low-level components and data
        • hierarchy
          • allows for inherited attributes and behavior
          • great for incremental development
        • modularity
          • functionality is broken into modules that accomplish only one task
          • number of smaller subproblems work together
        • polymorphism
          • ability to interact with classes without knowing which class it is
          • by implementing, compartmentalized components can be explained without affecting overall architecture
  • History of OOP
    • started in 1960’s
    • PHP3 introduced OOP in 1998
    • PHP4 added functionality in 2000, but had problems
    • PHP5 (2204) featured many improvements
      • extensive rewrite of object handling
      • Zend engine 2 – comprehensive feature set and improved performance
      • full object model
  • Defining a class
    • Naming conventions
      • for readability, name files in logical patterns, for this first class example:
        • class.address.inc
          • class tells that this is a class file
          • address tells what the class is going to deal with
          • inc tells that this file is to be included and not run on its own
      • In PHP, class definition always begins with the keyword class, followed by name of class
        • class name must start with letter or underscore
        • remaining characters must be letters, numbers, or underscores
        • there is no limit on length of class names
        • best practices
          • use upper camel case naming
    • A class can have any number of member variables, known as properties
      • defined as public, protected, and private
        • refers to scope of visibility
        • properties are declared like regular variables, with same naming conventions
        • best practice is to use lower camel naming
          • first letter is lowercase
          • avoid naming a public property is underscore at beginning
          • when declaring a property, you can initialize with a default value, but must be a constant value and not dependent upon anything else
      • visibility of property or method is defined as public, private, or protected
        • public methods can be accessed and manipulated by anything that can be referred to object
        • ex. public methods can be exposed as part of API
        • if protected, members can only be access within class itself or by inheriting or inherited class
          • a class can have all properties and methods of another class
          • class that is inheriting is child
          • class that is giving properties is parent
          • most common scope restriction when restricting visibility
          • to make this visually different, prepend an underscore
        • if private, only the class that has private members can access method or properties
          • used less often as it causes headaches
    • PHP Overloading
      • dynamically create property or method that
        • hasn’t been declared
        • is not visible in current scope
      • processed using magic methods
        • collection of specialized methods that are executed in response to php event
        • name prepended with two underscores
          • __construct()
          • __toString()
            • not the double underscore
        • there are about one dozen magic methods in PHP
      • Magic Methods can be useful
        • trigger custom behavior upon specific event
          • ex. attempting to access missing property or method
        • customize object creation
        • set defaults that aren’t available at runtime
      • Magic Method issues
        • Magic Methods have overhead that makes it 3 – 20 times slower to resolve
        • they ignore score and can expose hidden property or method
        • breaks IDE code completion
          • IDE can’t follow logic
      • Tradeoff
        • it may be worth the IDE warning to reveal some contextually responsive code that you can’t access any other way
        • performance difference is mostly negligible
        • customize scope controls
      • Magic Methods are public
    • As of PHP 5, developers can declare magic method to initialize new object before it is used
  • Using the static keyword
    • if needing to access property or class without overhead of instantiating class, can use static keywords
      • depending on class, that instantiation might include database calls or 3rd party support
    • avoids need for global scope
    • single instances of class and share across application
      • must have global mechanism to restrict creation of instances
    • static keyword allow method and processes to be accessed without instantiation
    • properties are stored at class level, not at object level
    • helps to keep track of instantiated objects
  • Scope Resolution Operator
    • also called double-colon ‘ :: ‘
      • this is a token that allows access to static, constant, and overwritten properties and methods
      • need name of class followed by double colon
        • class::method()
        • class::$property
  • Class Constants
    • property with a value that never changes
    • useful for defining error codes or things that have no need to change
    • Implementation
      • ALL_CAPS_SEPARATED_BY_UNDERSCORES
      • they should only contain simple values, likes strings, booleans, integers
        • no arrays
      • to define constant, start with const followed by NAME_NO_DOLLAR_SIGN = simple value;
      • there is no functional difference between having raw numbers and constants
        • they can be reference accross the application as constants
  • Static Methods vs. Regular Methods
    • similarities
      • naming convention is same
      • it can have scope
      • it returns a value
    • differences
      • cannot use $this pseudo-variable
        • results in fatal error
      • use self keyword
        • self::$property
  • IMPORTANT – difference between ‘ and “ – single-quoted strings are plain text with virtually no special case whereas double-quoted strings have variable interpolation (e.g. echo “Hello $username”;) as well as escaped sequences such as “\n” (newline.)
  • MySQL Improved Extension or MySQLi
    • offers both an object-oriented and procedural API to connect to DB
    • interacts with database
    • usually optimal to have only one connection to the database
      • best to control access and restrict number of connections
  • Inheritance
    • a fundamental object oriented principle
    • it is a relationship between classes and their instantiated objects
      • a class can be a subclass (child) of another class (parent)
      • useful for defining common functionality
      • allows for the addition of new functionality to a common class
        • when you have a child or a parent class, the child extends the parent class
    • a class must be defined before it can be extended
    • if you have a bunch of classes, explicitly adding them to document can become unwieldy
      • Autoloading
        • autoloading can be used to include missing class definitions
        • this can help future-proof application to allow for any new classes you create
    • Extending –
      • classes can extend only one class’s methods or properties at a time
        • cannot specify multiple classes to extend at one time
      • can extend a class that extends another class
      • use ‘extends’ keyword to indicate that a class will extend another
  • Abstracting
    • Introduced in PHP5
    • if class is defined as abstract, in cannot be instantiated
    • if class is abstract, any class that extends parent class must also be abstract
    • if class has an abstract method, then the class itself must be abstract
    • Approaches to initialization
      • Abstract __construct – is a fragile and unwieldy way
      • instead create abstract method to initialize object and call that from abstract class constructor
    • Abstract Scope
      • methods that implement an abstract method must have some scope or something less restrictive
        • public must stay public
        • private can be made public
        • this prevents unexpected behavior
  • Sharing Interfaces using Polymorphism
    • define an object interface
      • specifies methods that a class must implement
        • but doesn’t say how methods should be implemented
      • similar to abstract class
        • except that abstract class can have scope and method defined
        • interfaces have every single method as abstract and public
      • can have constants that cannot be overwritten
      • interfaces can extend other interfaces
      • sharing common application program interface between classes is polymorphism
        • when naming interfaces, try to be as generic as possible while still being identifiable across processes
        • a model is responsible for managing data, storing and retrieving entities
      • Final keyword prevents child classes from overriding method
        • cannot be extended
  • IMPORTANT – Methods are functions inside classes, while functions aren’t class specific
  • Overriding
    • a technique of re-declaring a method, property, or constant
    • done to define new or altered behavior
    • cannot specify a stricter scope
    • to override, in child class, declare the property
    • overriding a constant works the same
      • cannot redeclare constant from interface
    • overriding a method
      • new method must have same number of arguments
        • constructors is the exception
      • can call parent class methods and properties
        • useful to extend functionality without reinventing the wheel
  • Cloning and comparing objects
    • might want to make a backup
    • or as a shortcut for a similar object
    • to create a copy, use the clone keyword
    • comparison operator “==” checks to see if properties are the same
    • identify operator “===” checks to see if properties are same and it is an instance of same class
  • References
    • in php, a reference is an alias
      • multiple variables can write to same value
    • Object variables are different in that they do NOT contain the object itself, only object identifier
  • Standard Class
    • a standard class is the result of typecasting a value of any type to an object
    • won’t have any methods, but will have values
    • if you typecast an object to an object
      • no change or modification
    • if you typecast an array to an object
      • the result will be an object with properties named for the keys of the array and values corresponding to the array values
    • Using Standard Classes
      • returning a defined data structure with fixed branches without nesting
      • shorthand – takes less characters to access a property than to specify a key
      • can use standard object when interacting with method that is looking for an abject with particular properties but isn’t checking for the class
        • $array[‘key’] = ‘value’;
        • $array->key = ‘value’;
      • standard objects can be created with fetch argument in MySQLi
  • Error Handling with Exceptions
    • refers to methodology that responds to abnormal or exceptional situations that often arise
    • in PHP, exceptions are thrown, then caught
      • to catch exception, surround code in try block
        • if exception is not caught, PHP fatal error occurs
      • to throw – throw new Exception(‘parameter’);
    • exceptions are more forgiving and logical way to handle errors or extraneous circumstances
      • instead of halting execution or displaying error, program is given chance to recover
  • Identifying the Singleton Pattern
    • OOP offers a number of reusable solutions to common problems within a given context
      • called Design Patterns
        • Singleton pattern restricts instantiation of class to one object in order to coordinate actions throughout system
          • think database class example
          • common use of singleton pattern is lazy initialization, where a property defaults to NULL
        • Factory Method Pattern
          • creates objects without specifying the exact class of the object
        • Strategy Pattern
          • consists of family of interchangeable algorithms which perform a task
          • also a mechanism to determine which strategy to use to accomplish task
  • Namespaces
    • a way of encapsulating classes, functions, and constants to solve problems for authors of reusable code
      • naming collisions
      • ability to alias (shorten) long names
    • check http://php.net/manual/en/language.namespaces.php for more info on namespaces
  • Next Steps