Category: php

  • ClockInterface – why we need it and how to use?

    ClockInterface – why we need it and how to use?

    A few months ago a new standard was proposed to PSR and then accepted. Its name is PSR-20: Clock.

    And here is a short introduction from that document:

    Creating a standard way of accessing the clock would allow interoperability during testing, when testing behavior that has timing-based side effects. Common ways to get the current time include calling \time() or new \DateTimeImmutable('now'). However, this makes mocking the current time impossible in some situations.

    Basically, it explains everything you need to know. I came across an extremely similar solution on my previous work. “Great minds think alike.”

    The solution is really simple. Just look at the proposed interface:

    namespace Psr\Clock;
    interface ClockInterface { 
        /** * Returns the current time as a DateTimeImmutable Object */ 
        public function now(): \DateTimeImmutable; 
    }

    Let’s briefly consider how to use it in our “application”.

    First, we need to implement that interface:

    namespace ExampleApp\Clock;
    use Psr\Clock\ClockInterface;
    class DateTimeClock implements {
        public function now(): \DateTimeImmutable {
            return new DateTimeImmutable();
        }
    }

    And now we can use it in our application code:

    namespace ExampleApp\Log;
    use ExampleApp\Clock\DateTimeClock;
    use Psr\Clock\ClockInterface;
    class Entry {
        public function __construct(
            public \DateTimeImmutable $time,
            public string $message
        ) {}
    }
    class Logger {
        public function __construct(private ClockInterface $clock) {}
        public function createEntry(string $message): Entry {
            return new Entry(
                $this->clock->now(),
                $message
            );
        }
    }
    class LoggerFactory {
        public function __invoke(): Logger {
            return new Logger(
                new DateTimeClock()
            );
        }
    }

    Without ClockInterface we would probably just create a new instance directly: new \DateTimeImmutable(). And that would be really hard to test. Tests for calls to system API become tricky and flaky. But with the new interface, they become much easier and stable:

    namespace ExampleAppTest\Log;
    use ExampleApp\Log\Logger;
    use PHPUnit\Framework\TestCase;
    use Psr\Clock\ClockInterface;
    class LoggerTest extends TestCase {
        public function testCreateEntry_MessageGiven_ReturnsMatchingEntry(): void {
            $clock = $this->createMock(ClockInterface::class);
            $clock
                ->method('now')
                ->willReturn(
                    new \DateTimeImmutable('@1')
                );
            $logger = new Logger($clock);
    
            $entry = $logger->createEntry('a');
    
            $expected = [
                'time' => 1,
                'message' => 'a',
            ];
            self::assertSame($expected, $this->exportEntry($entry));
        }
        public function exportEntry(Entry $entry): array {
            return [
                'time' => $entry->time->getTimestamp(),
                'message' => $entry->message,
            ];
        }
    }

    Just imagine how you’re trying to catch a second or testing the period without this interface and tests fail in CI, because they run too slow or for any other reason. Probably you decide not to test time then and at some point it appears that a bug was introduced exactly in this place.

    I suggest considering using this new interface and make your life just a bit happier.

  • An alternative for a DI-container in WordPress plugin development

    An alternative for a DI-container in WordPress plugin development

    Briefly, the dependency injection helps us to work with dependencies: makes them observable and enables to substitute them whenever we need it.

    My choice of preference is to inject dependencies through a constructor. Here, we have both the observability and the replaceability. As a bonus, the object is completely instantiated and ready for future work. However, it becomes harder to create new objects and our code significantly suffers if we try to do that in a straightforward fashion by adding a few arguments to the constructor call. As we (usually) want to maintain testability and flexibility of our code, we have to extract the creation of the object in a factory.

    The popular approach here is to use the DI-container for that purpose. The major PHP frameworks, like Laminas and Symfony, have their own implementations. Sometimes they can handle everything for you: you just have to configure the container and follow a few simple rules. There are also framework-agnostic solutions that you can add to the app.

    About a year ago, I joined Automattic and dived into WordPress plugin development. I found a lot of traditions and conventions here. From my perspective, some of them are outdated, sometimes are toxic (in terms of software health) and need a revision. For example, it is really hard to write unit tests there. If you check popular plugins’ code you probably find some unit tests, but those are a mixture of integration tests and unit tests. I will not develop this topic here, but it might be interesting to discuss it later.

    I started experimenting with writing testable code, but the conventional approach of creating objects and introducing dependencies was blocking. To write a “pure” unit test, you need to have an opportunity to substitute the dependency, and that’s hard when it is instantiated deep in the roots of your logic.

    I tried to introduce a DI-container in my experimental project, but it turned out that you need to carry the container everywhere through the code to make it available. One option was to make it global: use global variable sounded terrible for me. Another version of the global state here was to use a function from the global state or a singleton.

    I tried to find a tradeoff. But then I realized that I don’t need a container as an external library. If I’m okay with a static factory, it is easier to write the simple one on my own.

    I remembered that approach from The Art of Unit Testing by Roy Osherove.

    You create a class with a static method that creates an instance of a class and returns it. However, you also have an option to substitute the returning value: for tests, for example.

    If you’re interested in how to implement this approach, you can check WPAL, my attempt to build an abstraction over the WordPress API.

    Here is the excerpt from the ServiceFactory class that creates the implementation for the Hooks abstraction:

    class ServiceFactory {
        /**
         * @var Hooks|null
         */
        private static $custom_hooks;
    
        public static function set_custom_hooks( ?Hooks $hooks ): void {
            self::$custom_hooks = $hooks;
        }
    
        public static function create_hooks(): Hooks {
            if ( self::$custom_hooks ) {
                return self::$custom_hooks;
            }
            return new WpHooks();
        }
    }

    The worst part of this approach, from my point of view, is that you create dependencies inside the constructor of a dependant. Not providing those dependencies through constructor’s arguments, we make them less visible. If you look at the constructor’s code, everything is well observable, and the object is completely ready for use after the constructor call. So, that’s my trade off here.

    This is how the usage of the ServiceFactory looks like:

    class Example {
        /**
         * @var Hooks
         */
        private $hooks_api;
    
        /**
         * @var string
         */
        private $plugin_file;
    
        public function __construct( string $plugin_file ) {
            $this->plugin_file = $plugin_file;
            $this->hooks_api = ServiceFactory::create_hooks();
        }
    
        public function init() {
            $this->hooks_api->add_action( 'init', [ $this, 'register_taxonomies' ] );
            $this->hooks_api->add_action( 'init', [ $this, 'register_post_types' ] );
        }
    
        public function register_post_types(): void { /* ... */ }
    
        public function register_taxonomies(): void { /* ... */ }
    }

    And the test for the init method:

    final class ExampleTest extends TestCase {
        public function testInit_WhenCalled_AddsAction(): void {
            $hooks_api = $this->createMock( Hooks::class );
            ServiceFactory::set_custom_hooks( $hooks_api );
            $contacts = new Contacts( 'a' );
    
            $hooks_api
                ->expects( $this->exactly( 2 ) )
                ->method( 'add_action' )
                ->withConsecutive(
                    [ 'init', [ $contacts, 'register_taxonomies' ] ],
                    [ 'init', [ $contacts, 'register_post_types' ] ]
                );
            $contacts->init();
        }
    }

    Talking about downsides of this approach, I can think about the global scope where the factory operates. On the other hand, DI-containers represent the same global scope problem, but covered with object-oriented tricks.

    Using a static factory looks preferably for me in the WordPress plugin development as we don’t have to bring another external dependency to the app, and the complexity of the solution looks relatively lower (comparing to learning, introducing and using the DI-container).

  • But these conflict with your requirements or minimum-stability

    Today I struggled with updating the library in the project. I just raised the version of this package, and now I was constantly getting:

      Problem 1
        - The requested package x/yz (locked at 1.2.3, required as ^1.2.4) is satisfiable by x/yz[1.2.3] but these conflict with your requirements or minimum-stability.

    I couldn’t understand anything at all because there were no stability changes, no sub-dependencies, and so on. I accidentally noticed a typo in my command:

    composer update x/yc --ignore-platform-reqs

    (the letter c instead of z at the end of the library name)

    But there is no such typo in the error message, and the error is not about a missing dependency.

    If you are experiencing the same problem but there is no typo, please read the article on the topic (ru).

  • isset vs. array_key_exists

    Совсем недавно моё невежество привело к тому, что система, к разработке которой я прикладываю свои руки и по возможности голову, на несколько часов оказалась частично непригодна для использования.

    Несмотря на свой уже достаточно богатый опыт работы с PHP и давнюю сертификацию по этому языку (хотя многие к ней относятся с юморком, всё же это какая-никакая базовая проверка знаний), я понятия не имел, что isset для элемента массива со значением null вернёт false.

    $arr = ['a' => null]; 
    isset($arr['a']); // false
    array_key_exists('a', $arr); // true
    (more…)
  • json_encode vs. serialize

    Итак, продолжение серии бесполезных исследований. В этот раз мы сравниваем несколько разные по сути функции, которые, тем не менее, часто используются с одной целью. В этом исследовании мы хотим представить массив значений (не объектов PHP) в качестве строки. Это исследование инициировал на работе Фархад Вильданов. К сожалению, ему это не помогло, так как он имел дело как раз с массивом объектов PHP.

    Что нам скажет serialize()?

    <?php
    ini_set('memory_limit', '4G');
    
    $initialArray = array_fill(0, 1000000, ['test value']);
    $start = microtime(true);
    $serializedA = serialize($initialArray);
    $end = microtime(true);
    
    echo 'serialize() string length: ' . strlen($serializedA) . PHP_EOL;
    echo 'serialize() time: ' . ($end - $start) . PHP_EOL;
    echo 'serialize() memory: ' . memory_get_peak_usage(true) . PHP_EOL;
    

    Вывод:

    serialize() string length: 36888902
    serialize() time: 0.43295097351074
    serialize() memory: 327155712
    

    Так выглядит тест для json_encode():

    <?php
    ini_set('memory_limit', '4G');
    
    $initialArray = array_fill(0, 1000000, ['test value']);
    $start = microtime(true);
    $json = json_encode($initialArray);
    $end = microtime(true);
    
    echo 'json_encode() string length: ' . strlen($json) . PHP_EOL;
    echo 'json_encode() time: ' . ($end - $start) . PHP_EOL;
    echo 'json_encode() memory: ' . memory_get_peak_usage(true) . PHP_EOL;
    

    Вывод:

    json_encode() string length: 15000001
    json_encode() time: 0.19829201698303
    json_encode() memory: 127401984
    
  • Разработка приложения с помощью Zend Framework 2

    1. Приложение необходимо разбивать на модули. Модуль включает в себя какую-то сущность и связанные с ней действия. Например, это может быть пользователь и контроллеры, отвечающие за вход/регистрацию, личный кабинет (настройки) и управление пользователями. Раньше я, разумеется, использовал модульность, но, как правило, модуль был достаточно весомым, он включал хоть и независимую (относительно) часть приложения, но все же там могли оказаться, например, и пользователи, и форум. Предложенная модель модулей в ZF2 предполагает соблюдения принципа единственной ответственности на более высоком уровне (по сравнения с классом или методом).

    2. Событийная модель — очень мощная штука. Она помогает следовать принципу единственной ответственности на более низком уровне. Простой пример: при регистрации пользователя надо отправить ему письмо (может, и что-то еще). В этом случае вы сохраняете пользователя и генерируете событие, например, “регистрация”. Все подписанные на это событие выполнят свое предназначение.

    3. Dependency Injection — об этом много и давно говорится на просторах интернета. Я рассматриваю DI с точки зрения удобства модульного тестирования, когда любую зависимость можно легко подменить моком. Например, при тестировании класса, взаимодействующего с базой данных, вам не хочется делать реальные запросы, так как вы тестируете в данный момент вовсе не это.  С другой стороны DI делает код более гибким, когда изменить используемый алгоритм не составит труда — нужно лишь передать новый объект, который будет реализовывать тот же интерфейс. Например, для создания пароля вам захочется изменить алгоритм на более надежный.

  • autotest для PHP

    Я последнее время немало человеко-часов провел в экспериментах с Руби и Рельсами (об этом я еще напишу отдельный пост). Вернувшись назад в мир разработки на PHP мне стало очень не хватать одной простой утилиты, к которой я успел так привыкнуть. Называется она autotest. Проблема в том, что она для руби. Я быстренько поискал в Гугле и на Гитхабе и не нашел ни одного решения на PHP (позже все же нашел несколько, но они мне все равно не понравились). А я верю в то, что инструменты для разработки на каком-то языке должны писаться на нем же. Хотя бы потому, что ты как разработчик на этом языке не будешь испытывать проблем, если потребуется что-то на скорую руку исправить или модифицировать. Тут руки зачесались, и я написал свой вариант автотеста.

    Прошу любить и жаловать — php.autotest.

    (more…)
  • array_map(‘intval’, $array) vs. array_map(function($val) { … }, $array)

    И я продолжаю серию своих никчемных исследований…

    <?php
    ini_set('memory_limit', '4096M');
    
    $array = [];
    for ($i = 0; $i < 1000000; $i++) {
        $array[$i] = (string)$i;
    }
    
    $start = microtime(true);
    $tmp = array_map('intval', $array);
    $end = microtime(true);
    echo 'array_map(\'intval\', $array): ' . ($end - $start) . PHP_EOL;
    
    $start = microtime(true);
    $tmp = array_map(function($value) {
        return (int)$value;
    }, $array);
    $end = microtime(true);
    echo 'array_map(function($value) { ... }, $array): ' . ($end - $start) . PHP_EOL;
    array_map('intval', $array): 0.47099804878235
    array_map(function($value) { ... }, $array): 2.9696278572083
  • array_key_exists vs. isset

    Очередное маленькое бесполезное исследование скорости работы двух похожих функций.

    Код и результаты, как водится, ниже.

    <?php
    
    $array = range(0, 1000000, 3);
    
    $start = microtime(true);
    for ($i = 0; $i < 1000000; $i++) {
        array_key_exists($i, $array);
    }
    $end = microtime(true);
    echo 'array_key_exists: ' . ($end - $start) . PHP_EOL;
    
    $start = microtime(true);
    for ($i = 0; $i < 1000000; $i++) {
        isset($array[$i]);
    }
    $end = microtime(true);
    echo 'isset: ' . ($end - $start) . PHP_EOL;
    array_key_exists: 0.13523197174072
    isset: 0.055444002151489
  • Обновление PHP в Mac OS X

    Сегодня мне рассказали про очень простой способ обновить PHP на локальной Mac OS X.

    Шаг 1. Сначала необходимо установить Xcode, если вы этого до сих пор не сделали. Запускаем его, идем в меню Xcode → Preferences… и выбираем тут закладку Downloads. Жмем “Install” напротив Command Line Tools. Шаг 1 завершен, в дальнейшем при очередном обновлении этого делать уже не потребуется.

    Шаг 2. Снова, если не было это сделано ранее, устанавливаем Homebrew. Для этого достаточно выполнить команду:
    ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"

    На этом второй шаг завершен и его повторять также не потребуется впоследствии.

    Шаг 3. Переходим непосредственно к установке новой версии PHP. По адресу http://php-osx.liip.ch есть небольшой сайтик посвященный утилите для установки PHP. Смотрим раздел “One Line Installation” и копируем оттуда команду, соответствующую желаемой версии интерпретатора. Например, для PHP 5.4 это будет:
    curl -s http://php-osx.liip.ch/install.sh | bash -s 5.4

    Сегодня он установил мне PHP 5.4.15, который является самой последней версией в данной ветке.

    Тут необходимо заметить, что эта утилитка не заменяет установленный в системе PHP, поэтому по умолчанию будет работать старая версия. Чтобы это исправить нужно отредактировать (или создать) файл .profile, который находится в вашей домашней директории (то есть ~/.profile). В этот файл нужно добавить строчку, которая изменит путь поиска бинариков:
    export PATH=/usr/local/php5/bin:$PATH

    После этого нужно перезапустить терминал (или перелогиниться в нем), чтобы изменения вступили в силу.