Back to the blog

Object-oriented programming fundamentals in PHP

phpooparchitecture

Notes from the Object Orientation with PHP course at Alura, in Portuguese (which is why the examples use the Alura\Banco namespace).

MVC

Model refers to the layer that models our business — that is, the domain and the business rules. View is how that gets represented visually, and the connection between the two is handled by the Controller layer.

MVC was conceived in the 1980s, during the development of Smalltalk applications.

The four pillars of object orientation

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

One of the ways to reuse code is to make a class extend another — that is, inherit everything a base class has and add specific behaviors.

But it's worth stressing that inheritance is not the solution to every code-reuse problem — it can often even be harmful.

It's still not 100% clear to me, but the article Como não aprender orientação a objetos: Herança (in Portuguese) is worth reading. I saved the link to reread later, with more object-orientation experience, and again a few months after that — it tends to make more sense with every reread.

Access modifiers

In PHP we have three access modifiers for the members (attributes and/or methods) defined in our classes: public, protected and private.

public lets everyone access the member, including outside the class where it was defined, through an instance. protected grants access to the current class and its child classes. private grants access to the current class only.

Namespaces

By defining namespaces, we can easily have two classes with the same name in different namespaces. A class named Conta (account), for example, can have a different meaning in the login module and in the accounts module. Using a root namespace for our application, we also avoid conflicts with external packages we may come to use.

It is very useful and good practice to use namespaces to separate the classes in our application. To make good use of this feature, there are a few details we should understand.

When we define a class without declaring its namespace, it is created in PHP's default namespace. This namespace has an "empty name", meaning a Conta class without a namespace has \Conta as its full name.

If, inside a class with a defined namespace, we need to access classes from another namespace, we have to add a use statement or spell out the full name (namespace + class name).

Being in the Alura\Banco\Modelo\Conta\Conta class, for example, and wanting to access the Alura\Banco\CPF class, we need to state the full class name, or add use Alura\Banco\CPF at the top of the file — which lets us use just CPF as the name in the rest of the file.

Another interesting detail: if we need to "import" (with use) more than one class from the same namespace, we can do it on a single line, wrapping the class names in braces. For example:

namespace Alura\Banco\Conta;

use Alura\Banco\{CPF, Endereco};
use \SplFileInfo;

class Conta
{
    public function umMetodoQualquer()
    {
        // ...
        $cpf = new CPF();
        // ...
        $endereco = new Endereco();
        // ...
        $fileInfo = new SplFileInfo();
        // ...
        $fileObject = new \SplFileObject();
        // ...
    }
}

Topics to remember

  • We can split our classes into namespaces, just like we split files into folders.
  • By separating classes into namespaces, we can have classes with the same name in different namespaces.
  • Using a root namespace (called a vendor namespace in some of the literature), we can avoid conflicts with classes from external packages we may use.
  • To use a class, we need to import it with use or state its full name (with namespace) everywhere it is used.
  • With a PHP autoloader (spl_autoload_register), we can avoid using require over and over to include every file the program needs to run.
  • An abstract class is not concrete — it is not complete yet and needs to be extended to make sense. That's why we can't instantiate objects directly from abstract classes.
  • Abstract methods are a way to "force" child classes to implement a given method; only abstract classes can have abstract methods.
  • The ControladorDeBonificacoes class, for example, represents the employee bonus control feature. Through an instance of it, we can add employees and, at the end, retrieve the total spent on bonuses. A model class like Conta, on the other hand, represents something that exists in our domain.

Polymorphism

This 4th principle is directly tied to the 3rd (inheritance), since it's through inheritance that we achieve polymorphism.

Polymorphism is the ability of an object to be referenced in multiple ways (careful: it doesn't mean the object keeps transforming itself — quite the opposite, an object is born of one type and dies of that type; what can change is the way we refer to it).

With that, we can, for example, receive a Funcionario (employee) as a parameter in a function or method and pass in a Gerente (manager). We can refer to the Gerente instance in more than one way, and that can be useful in many cases, as we saw throughout the course.

Folder organization

During the Object Orientation trainings, we organized our folders using a fairly common structure.

There is a root folder for our code (src), which also makes it easier to follow PSR-4.

Inside this root folder, there are subfolders that identify responsibilities in our system.

Architecture

Organizing the folders in our code is a very simple beginning of a study on architecture. How to organize our project is a very important subject, and there are plenty of books, talks and content in general about it.

Alternatives to our approach

It is very common — and recommended by many — that instead of separating the subfolders by responsibility (Model, Service, etc.), we separate them by domain concepts, similar to what we did inside the Model folder. Dedicated studies on architecture and code design cover these concepts in much more detail.

Relationships between models

Through method definitions, we declare the relationships, returning the type of that relationship. For example: belongsTo, hasMany, hasOne, belongsToMany.