jeudi 10 août 2017

What is this pattern/object called?

I've recently found something in a legacy PHP app, new code that was kind of extending old code was built using objects like this:

<?php

class FacadedObject
{
    private $data = [];

    /** string A example const */
    const $dtFormat = 'Y-m-d H:i:s';

    /** \DateTime A example property */
    private $realStartTime;

    public function __get($name)
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        return null;
    }

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __isset($name)
    {
        return isset($this->data[$name]);
    }


    public __construct($data = null)
    {
        if ($data !== null) {
            $this->data = $data;
        }

        $this->prepare();
    }


    private function prepare()
    {
        /* right here objects are created from legacy
           data (SQL results, date strings to datetime objects, ...)
           to be used in methods, this almost always is neatly
           structured like 
           $this->prepareDateTimes() 
           $this->sortEventsByRealTime() */

        $this->realStartTime = DateTime::createFromFormat(self::dtFormat, $this->data['legacy_date_alias']);

    }

    public function aExampleFunction()
    {
         /* This function would probably use only data that was
            prepared earlier, maybe a few values from the original,
            internal array */

         return ($this->data['a_long_and_legacy_sql_alias'] && $this->realStartTime->something() >= 0)
    }

}

It can be seen that it tries to achieve some kind of facade over old DB data for implementing new functionalities. Some of them use ArrayAccess to fake being the original arrays.

The project had no real Models - just a DB layer for getting arrays of data.

Is this way of extending plain arrays with Model-like functionalities called something? Or is this a wrong implementation of an existing pattern?

Aucun commentaire:

Enregistrer un commentaire