Memoize Method Calls in PHP with Cache Decorators

A “memoized” function is a function that only calculates the return value for each combination of arguments once and returns the previously calculated value if the function is called a second time with the same arguments.

In PHP, I often see this implemented with code like this:

class ProductRepository implements ProductRepositoryInterface
{
    private $products = [];
    public function product($id)
    {
        if (! isset($this->products[$id])) {
            $this->products[$id] = $this->load($id);
        }
        return $this->products[$id];
    }

    private function load($id) { ... }
}

Continue reading “Memoize Method Calls in PHP with Cache Decorators”

PHP: Using class_alias to maintain BC while moving/renaming classes

Sometimes you want to rename a class or move it to a different namespace. But as soon as it is used anywhere outside the package, this is breaking backwards compatibility and should not be done lightheartedly.

Luckily there is a way in PHP to have both, the old class and the new class, while deprecating the old one: class_alias().

How to use class_alias() without messing up class autoloading

Let’s say, the old class is OldClass and we want to rename it to NewClass.

First, we rename the class and move it from OldClass.php to a new file NewClass.php.
Continue reading “PHP: Using class_alias to maintain BC while moving/renaming classes”

Design Patterns for Framework Agnostic Extensions/Plugins – Autoloading

Part 5 of my blog series on integer-net.com about framework independent code is out: Using Advanced Autoloading. This one is only relevant for the integration of legacy applications that do not use composer autoloading yet (Magento 1).

Previous Parts

  1. Introduction: Shared Code For Magento 1 and Magento 2 Extensions
  2. Accessing Configuration Data
  3. Using Dependency Injection
  4. Building Bridges
  5. Preparing Data For Output

Design Patterns for Framework Agnostic Extensions/Plugins

My new article series on integer-net.com introduces useful design patterns for decoupled Magento extensions, which are divided in two parts: the Magento module and a framework independent (framework agnostic) library, that is reusable for Magento 1 and Magento 2. Of course, the same principles can also be applied to other frameworks and applications.

Diagram of Magento 2 Extension Dependencies for Framework Agnostic Modules

It will not cover the refactoring process from existing extensions to this model, that’s a different topic and I am going to talk about it at Developers Paradise 2016 in Croatia. Stay tuned!

The first part is about accessing application configuration, using Configuration Value Objects.

Continue reading on integer-net.com