PHP RFC: Comprehensions

Another interesting RFC recently landed to PHP community. So far the easiest way of explaining comprehensions for me comes from Python world:

Comprehensions are constructs that allow sequences to be built from other sequences.

Here’re some examples from List comprehensions in Python:

def palindromes(strings):
    return [s + s[::-1] for s in strings]

def starting_with(letter, names):
    return [name for name in names if name[0].lower() == letter.lower()]

JavaScript, however, decided to remove its support from standard in favour of filter/arrow/map functions.

The array comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using Array.prototype.mapArray.prototype.filterarrow functions, and spread syntax.


Speaking of PHP RFC, that’s what we might get if RFC gets approved:

$gen = [for $list as $x if $x % 2 yield $x*2];

//equivalent to:

$gen = (function() use ($list) {
  foreach ($list as $x) {
    If ($x % 2) {
     yield $x * 2;

Personally, I would vote in favour of this. Maybe, it’s nostalgia about Perl one-liners and how elegant you can solve some basic stuff. I think PHP needs this syntactic sugar, giving people choice of using closure calls and comprehensions.

CakePHP Time formatting: year of “week of year”

While jumping between PHP and JavaScript – one of the most annoying things is dates handling.

Recently, one of the clients reported that, while using our app for appointments and work schedule – they lost one of the working days. Client’s worker was supposed to work on the 31st of December 2019.

Firstly, working on the 31st is an achievement. Since we can’t affect it, “bug report” was filled on our end. After few hours of debugging, the problem was found.  

CakePHP uses Cake\I18n\Time class to handle date time. It’s an ancestor of chronos library under the hood. As a result, when you’re working with DateTime object, the formatting slightly changes. Thankfully, I was not the only one who accidentally used “year” notation wrong. 

use \Cake\I18n\Time;

$badDayToWork = '2018-12-31 09:00:00';
$time = new Time($badTimeToWork);

Cake\I18n\Time Object(    
    [time] => 2018-12-31T09:00:00+02:00    
   [timezone] => Asia/Nicosia    
   [fixedNowTime] =>

print_r($time->i18nFormat('YYYY-MM-dd HH:mm'));

// Output: 2019-12-31 09:00.

One tiny bit I missed was incorrect “Y” formatting flag.

yyyy (year)
YYYY (year of “Week of Year”)2019

In this case, 2018-12-31 falls on Monday, so according to ICU documentation – it’s year 2019.

Psalm – static analysis of PHP

Once every blue moon, I dive into Github repositories to check for something useful for my everyday routines.

This time, I stumbled upon Psalm from Vimeo. 

Psalm is designed to understand that complexity, allowing it to quickly find common programmer errors like null references and misspelled variable names.

vimeo Psalm documentation

I’ve been using phpstan for basic code static analysis for a while. I was running it with various rule levels, depending on the complexity of the codebase.

So far, benchmarking an output from both varies on the same codebase. Psalm managed to find more inconsistencies in the code – looks like it’s worth giving a shot.

CakePHP CsvMigrations: prototype in 3 2 .. Done!

Every programmer is tired of coding yet another login form. Yet another CRUD view module. So today I’ll show you an example where our laziness can get you building prototype systems without a single line of extra code.

One of the tasks, that we had to face when developing Qobrix CRM, was fast prototyping of the system. The result of ultimate laziness and DRY concept resulted in cakephp-csv-migrations plugin that we try to use pretty much everywhere, while delivering the system.

Your application is not unique

Whatever you request for your Prototype is mostly based on same functionality:

  • CRUD views
  • Basic CRUD actions
  • Event/Trigger system that allows you mutating the data

If we dive deeper into these points, whatever you work with is form based – your input fields are the minimum atomic unit of interaction: strings, longtexts, datetime. Looks familiar? Exactly, database data types.

In certain cases, you store dates in strings, names in varchars, or even longtext. At this moment we come to the point of having a binding mechanism of your application logic with your storage engine. For simplicity reasons – I’d base this example on RDBMS like MariaDB, MySQL, etc.

Changing those binding might be difficult for the user. As the supplier of the system, you don’t know who’s going to deal with the system: some companies don’t have IT departments, but need to modify things rapidly. The same applies to developers level of expertise for the system. We wanted to make it as simple as possible.

Preparing the App

Note: If you already have a CakePHP application running, just composer require qobo/cakephp-csv-migrations, and you can skip this part.

Theory is boring without examples, so I’ll try to show you a basic thing on how to expand the system with extra modules. For simplicity reasons, I’ll base it on project-template-cakephp template that we frequently use. It already has some dependencies, as well as cakephp-csv-migrations plugin as part of cakephp-utils.

composer create-project qobo/project-template-cakephp baking_app
cd baking_app
./bin/build app:install DB_NAME="baking_app",CHOWN_USER=$USER,CHGRP_GROUP=$USER,PROJECT_NAME="My Baking App"

That’s enough to check that your app is up and running. For basic creadentials and stuff, you can check .env file that was generated by the Robo build scripts.

Baking Recipes Module

Here comes the baking part. We’re going to make a simple recipes module to store our favourite recipes.

./bin/cake bake csv_module Recipes
./bin/cake bake csv_migration Recipes

First command will create dummy MVC instances for CakePHP: Model/Entity, Controller and ApiController files, based on which the second script will verify that you can bake a migration script (based on Phinx migrations).

If you’ll look into migration file created in config/Migrations/<timestamp>_Receipts<timestamp>.php, you see something like that:

use CsvMigrations\CsvMigration;

class Recipes20180126154309 extends CsvMigration
        public function change()
        $table = $this->table('recipes');
        $table = $this->csv($table);

        if (!$this->hasTable('recipes')) {
        } else {

        $joinedTables = $this->joins('recipes');
        if (!empty($joinedTables)) {
            foreach ($joinedTables as $joinedTable) {

Where are the fields? That’s the point where all the magic happens.

CsvMigrations plugin provides you with vast number of input types that can bind to basic data types of your database. They’re stored in config/Modules/Recipes/db/migration.csv file. We’ll expand it a bit:


I’ve added name, type and recipe fields that can be handled by varchar and longtext data types in the database. Let’s cook it:

./bin/cake migrations migrate

And we are done! You noticed list(<list_name>) type used within migration.csv. This FieldHandler type is used for defined option lists for rendering Select boxes in you form. The lists are stored in config/Modules/Common/lists/meal_types.csv:

Where are my views?

If you start up the application, and navigate to http://localhost:8000/recipes/add you’ll see something like that:

add recipes form

Now we need to add fields to CRUD form. CsvMigrations can help you with that. All your form fields are located in config/Modules/Recipes/views:

Details,name, meal_type

The example above is for add/edit.csv files being modified. Reloading the add page:

add form complete
add form complete Complete add form

Now you’re ready to work with basic CRUD. All the common CRUD logic is already located in cakephp-csv-migrations plugin that will handle API requests for the index page for DataTables grid loading. If you want to change its behavior, you can always override action methods in `RecipesController`.

CakePHP: Interview with Larry E. Masters

Interesting interview with one of the core members of CakePHP community – Larry E. Masters.

Throughout the interview Larry covers CakePHP Framework history, as well as covering major milestones of CakePHP 3.x version.

If you’re still into 2.x then it’s time to upgrade, as it brings some nice perks.

More flexible code, and massive performance boost.