RSS
 

CakePHP 3.6 is coming

14 Mar

The first betas have landed already. Make your plugins and apps 3.6-ready now.
It is actually rather easy – better to be proactive now and have a small migration path than a big fallout and some surprises in a few weeks or months.

Prepare your Application

First read the 3.6 migration guide to get a grasp of the upcoming changes.
Deprecations ignored (easy ones, more later), there are not too many changes – especially no heavy ones. All in all this should be a very smooth upgrade from previous 3.x versions.

Now for the actual upgrade we have a few important issues to talk about:

Regressions

3.6 might introduce accidental regressions or issues that your app can not deal with. Those should be either fixed or outlined in the documentation and migration guide.
You can spend a few minutes here to find out early on how compatible your app is to a new minor version. Execute

composer require cakephp/cakephp:"dev-3.next as 3.5.14"

if you want to check the latest 3.6 version faked as 3.5 (due to the constraints). You can of course try 3.6 here as aliases, as well (as long as no constraints locks it down to ~3.5.x).

Note: For some plugins there might be already a 3.next branch (or even tags), as well.

Report or PR any issues you find and help to make the 3.6 release as smooth and BC as possible.

Migration path

Always keep up with minors in the framework. So at this point I expect everyone to be already running on CakePHP 3.5 for a while.

You can already have fully removed any deprecation of 3.4 or 3.5, which will further make the migration path smaller and easier to review.
Since 3.6 will trigger actual deprecation notices, this is really advised to do early on.
Once you actually switch to 3.6 you can actually silence the deprecations for the first run to verify functional compatibility by setting the error level in your app.php configs:

    'errorLevel' => E_ALL & ~E_USER_DEPRECATED,

Read the 3.6 migration guide for any functional upgrade that might be necessary, those should be applied first.

Once you established functional BC, you can start replacing all deprecations and afterwards again all tests should pass.

Tip: Try not use the above silence as a production default if possible. Instead try to remove those asap. But if not all plugins are updated yet, or do you don’t have the time to fix all of them right now, it is acceptable to just keep the deprecations silenced for the time being.

Migration tooling

Until now there was the CakePHP Upgrade tool which really helped a lot for the migration.
And it still does for a small subset, e.g. upgrade skeleton syncs the skeleton files from the latest cakephp/app repo into your app.
So it might not be completely dead just yet. If you are even below 3.5, definitely check it out.

But regex can only do so much. For more complex issues and especially all the deprecations there are now more modern and less error prone solutions available.
There is a very useful PHP tool that can help with deprecation replacement called rector.
It introspects the code and can very reliably identify and replace code pieces.

I tried it and using

composer require --dev bamarni/composer-bin-plugin
composer bin rector require --dev rector/rector:'dev-master' nikic/php-parser:'4.0.x-dev'
// lets dry-run for src/ directory
vendor/bin/rector process src/ --level cakephp36 --dry-run

it will show you what it would change as diff. Without --dry-run it will then actually run the upgrade. Make sure you committed all files or made a backup.

Tip: If it takes too long, just run it on each subfolder, e.g. src/Model, …

You can take a look at its CakePHP config. If there is anything missing, you can PR (pull request) your additions.

Plugins/Ecosystem

If you encounter issues with plugins or alike, open a ticket or better yet a pull request to get these things fixed ASAP.
This should ideally also be done pro-actively before you actually start upgrading your code-base, so that there is no time-bottleneck.

In case there really is something stuck, you can make a fork and use a tmp branch of master on your side for the upgrade.
Your composer.json would then point to dev-master of your repository fork and contain a repositories link so that composer knows to look there:

  "repositories": [
    {
      "type": "git",
      "url": "git@github.com:your-name/plugin-name.git"
    }
  ],

Once there is a tag with the fixed code in that original repository, you can remove and use the tagged release again.

Prepare your Plugins

This actually brings us the next point – if you are maintainer of a plugin yourself.

Having so many deprecations throughout 3.x it becomes more and more difficult to keep track of when methods were added and since what version you can use them, or not use others anymore.
With 3.6 this is more important than ever since this now adds deprecation warnings emitted for deprecated usage.
So make sure that if you start supporting 3.6 for your plugins, that your composer.json constraint towards cakephp/cakephp reads ^3.6. Users need to know if they can pull your version without the application breaking.

First of all: Make sure you support 7.2 in your Travis test matrix. There are quite some changes hidden in count() usage that can easily break your code or at least emit warnings.

Secondly, make sure you got also older PHP and CakePHP versions properly regression tested.
I started to actually add the following trick into my plugins:

matrix:
  include:
    ...
    - php: 5.6
      env: PREFER_LOWEST=1

Then exchange the first before_script line composer install with

before_script:
  - if [[ $PREFER_LOWEST != 1 ]]; then composer install --prefer-source --no-interaction ; fi
  - if [[ $PREFER_LOWEST == 1 ]]; then composer update --prefer-dist --no-interaction --prefer-lowest --prefer-stable ; fi

This will make sure, composer uses the lowest possible versions everywhere.
You will now spot any wrong usage of methods right in your tests in Travis – if those are covered by tests, that it.
That’s why I think it is more valuable that the tests execute the code than having good asserts. Sure, the latter is also needed in some cases. But the mere fact that the code executes fine means already a lot, from syntax issues (based on the PHP changes even in minor versions) and interface issues to other more runtime issues.

A full working version can be seen e.g. in TinyAuth .travis.yml.

Try to support 3.5 and 3.6

It is usually best to not always jump right to the latest minor as minimum requirement. This makes it harder for folks on the previous minor to get patches and bugfixes.
Thus, with the new deprecation warnings, you might have to do the following if you use any deprecated functionality because of this:

Add <ini name="error_reporting" value="16383"/> into your phpunit.xml.dist file (see here for example).

Similar things can be required for tooling like PHPStan. The linked IdeHelper plugins also shows a solution for this using a shim.php file that contains

error_reporting(E_ALL & ~E_USER_DEPRECATED);

Icing on the cake

You want to go even a step further and get alerted early on if your plugin or app breaks with new minors or patches?

Most of the time I encountered CI fails and BC issues months after when I applied a new change to a plugin and suddenly tests that should have passed didn’t pass anymore.
In this case you can see that the core way of building a query has been changed and now has less () brackets in 3.5+. Notified about this I can just make the tests conditional on the CakePHP version and all is good again.

It is rather easy to enable a cronjob in CI (e.g. Travis) that runs nightly or weekly and alerts you of any failures of new releases.
This is an example of how to enable for Open Source plugins in Travis:

5.00 avg. rating (95% score) - 2 votes
 
No Comments

Posted by Mark in CakePHP

 

CakePHP Tips 2017 Part 1

14 Apr

Whoops as ErrorHandler

I recently switched to Whoops in my apps.
It provides a better exception rendering for development mode for most cases.

Just load the plugin (dereuromark/cakephp-whoops) and modify the bootstrap line:

//(new ErrorHandler(Configure::consume('Error')))->register();
(new \CakephpWhoops\Error\WhoopsHandler(Configure::consume('Error')))->register();

If you already have a src/Application.php and run a middleware setup, you also want to make sure you either remove the ErrorHandlerMiddleware there, or provide a custom one for Whoops.

You can test it for example with my sandbox app.
Check it out locally, set it up in minutes and give it a test run.

Jump from browser to IDE

With the Whoops error handler the probably nicest feature is the "click to IDE" one.
It allows to click on the class inside the displayed code piece and jump right into the IDE into the exact line of that file displayed in the browser stack trace.

Be more productive leveraging your IDE

Using the new IdeHelper plugin you can now not only bake annotations into new code, but also adjust
your existing code all the time.
The plugin provides a shell to quickly sync the existing annotations with your code.

This way you can maximize IDE compatibility and with that prevent obvious issues and mistakes.
The IDE will usually mark problematic code yellow (missing, wrong method etc).

It can also enable you to click through the classes and object chains which otherwise would just be plain text and have no typehinting.
Finally autocomplete will be available for all the "magically" provided classes and methods this way.

screenshot

This plugin is supposed to work with ANY IDE that supports annotations.
The plugin wiki contains even details and tips/settings for each of those IDEs – collected by the community.

Enable PHPStan in your app and plugins

PHPStan is a super useful static code analysis tool.
It will help you to find issues with your code way beyond what the test suite or IDE syntax checks can do.

For example, if you have two many different return types and only respect one of them, it will mark this as issue.
It will also tell you about interface mismatch or other similar code smells.

Adjust Travis

Add a new matrix row and a script call for that matrix entry:

...
matrix:
  include:
    ...
    - php: 7.0
      env: PHPSTAN=1 DEFAULT=0
...
script:
  ...
  - if [[ $PHPSTAN == 1 ]]; then composer require --dev phpstan/phpstan && vendor/bin/phpstan analyse -l 1 src; fi
...

Level 1 (-l 1) is the lowest level, once everything passes you can go up to level 5 currently. I recommend trying level 3, if possible.

If you need to ignore certain errors, you can use a custom phpstan.neon file in your /tests directory and then append -c tests/phpstan.neon into the command for travis.

vendor/bin/phpstan analyse -c tests/phpstan.neon -l 1 src

For me such a file looked like this, for example:

parameters:
	autoload_files:
        	- %rootDir%/../../../tests/bootstrap.php
	excludes_analyse:
		- %rootDir%/../../../src/TestSuite/*
	ignoreErrors:
		- '#Call to an undefined method Cake\\Datasource\\EntityInterface\:\:source\(\)#'

Don’t try to ignore too much, though – only "false positives" are recommended to be added here.

You can also write custom PHPStan extensions, see the current CakePHP core /tests/PHPStan folder for details.

Using it locally

I added this to my plugins’s composer.json files:

"scripts": {
    ...,
    "phpstan": "phpstan analyse -l 1 src",
	"phpstan-setup": "cp composer.json composer.backup && composer require --dev phpstan/phpstan && mv composer.backup composer.json"
}

This will allow local testing without messing up your composer file πŸ™‚
For app instead of plugin development you also want to backup-restore the lock file.

Now just run

composer phpstan-setup
composer phpstan

I bet you will find a few useful issues to resolve right on the first run of this tool.

5.00 avg. rating (93% score) - 1 vote
 
3 Comments

Posted by Mark in CakePHP

 

CakePHP Tips Winter 2016

31 Dec

This is literally my last blog post for the year 2016 πŸ™‚

Use the right DateTime typehint

If you are passing DateTime objects around in CakePHP, they are usually Chronos objects,
and either \Cake\I18n\Time or \Cake\I18n\FrozenTime then.
Both those are not suited as typehint usually, as both are fine for most plugin solutions and also
limit the user in what kind of class he uses. At least FrozenTime would be a bit better then Time.

But what would be the correct typehint? Use DateTimeInterface from PHP.

public function addRow(DateTimeInterface $date, $content, $options = []) {
    $day = $date->format('d');
    ...
}

It is fairly simple to typehint that we need a DateTime object without unnecessarily restricting the plugin to a specific subset.

Note: This is only valid if you are not modifying the object, otherwise use the concrete one. But you really should try to code "immutable" and rather clone and then modify without altering the original value.

Nullable database fields

Nullable fields in the DB should usually either be null or have a concrete value. For foreign keys as well as most integer, float and even string fields that means, that an empty string as input coming in should be transformed to this null value then for data integrity.
Unfortunately, the CakePHP ORM doesn’t do that out of the box for some fields.

Why is it an issue? Well, imagine you want to query for all with an empty value for a field.
Instead of a simple 'field IS' => null you then need to do a more complex ['OR' => ['field IS' => null, 'field' => '']] all the time.
And if you forget it in a single query they results will be inconsistent. That’s kind of bad.

The Shim.Nullable behavior can help here.
Once attached, it will take care of those values when saving and make sure you don’t end up with different null values in your DB.

Leverage Composer scripts

The new cakephp/app skeleton contains some new interesting gotchas regarding composer scripts:

    "scripts": {
        ...
        "check": [
            "@test",
            "@cs-check"
        ],
        "test": "phpunit --colors=always",
        "cs-check": "phpcs --colors -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests",
        "cs-fix": "phpcbf --colors --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests"

That basically standardizes and simplifies the way the test and sniff calls are executed.
Before it was php phpunit and a long vendor/bin/phpcs ... call, now it is always just composer test or composer cs-fix etc.
Even doing together now is easy with composer check.

My apps and plugins use the PSR2R sniffer version, but from the outside the commands are completely identical, which is nice.

Note: The vendor/bin/ prefix part (as you might have expected) is not necessary as Composer will still find the scripts just fine.

Testing different databases

Locally, testing the CakePHP core for example defaults to SQLite.
The other databases, as they would need to have a valid connection, are skipped.

But if you are working on a specific feature that would need those to test if it is working, you would want to use that one instead.
Thanks to getenv() usage we can easily exchange the connection via db_dsn.

In your console:

export db_dsn="mysql://root:secret@127.0.0.1/cake_test"

This expects a "cake_test" database set up, and an access with the username root and the password secret (vagrant default for CakeBox here).

For Postgres it would probably be something like postgres://postgres@127.0.0.1/cakephp_test.
CakeBox also ships with that out of the box. You might need to also install the extension before via sudo apt-get install php-pgsql.

When you now run php phpunit.phar from now on, it will use that connection until you switch it again (for that session).

0.00 avg. rating (0% score) - 0 votes
 
2 Comments

Posted by Mark in CakePHP

 

Emoji and CakePHP

11 Nov

You might think: Why do I care.
Well, you would be surprised – but pretty much any website with at least one form on the page will be affected here.
So anyone with even just a basic contact form should think about applying the following changes.

A wile back I got reports that one of my older websites has problems with emoji smileys and alike.
When browsing it with a mobile device and entering a native mobile smiley the emoji and all the following text would be lost when saving.
This was especially annoying with a longer conversation that you then have to retype – many people will not know why the text was truncated and will even run into the same issue again and again.

What’s the issue?

It turns out that native emoji are 4 byte characters, and the normal MySQL database, its tables and fields were all "just" utf8_unicode_ci and only supported less than that.

How to fix it?

First of all: BACK UP YOUR DATA!

With MySQL 5.5+ it is now possible to convert everything to utf8mb4_unicode_ci and then it will safely accept all those characters now, as well.

In your database.php in 2.x or app.php in 3.x you need to change the encoding from utf8 to:

'encoding' => 'utf8mb4',

Then you must convert your database, the tables and all their fields to to the new collation.
You can use my Setup plugin to automate this:

bin/cake Setup.DbMaintenance encoding

But with dry-run param -d you can also just output the SQL commands and manually run them via Migrations plugin, for example.

If you now paste emoji characters and store them, they should be visible just fine on your website now.
Also make sure sending emails, e.g. through a contact form, is working properly.

Troubleshooting

You can run into the following issue:

SQLSTATE[42000]: Syntax error or access violation: 
1071 Specified key was too long; max key length is 1000 bytes

In that case make sure you modify your fields here. With the 4byte length some fields cannot be varchar(255) anymore, but must be a bit less (250) in oder for the convertion to work out. You could also look into "innodb_large_prefix" and options to increase the limit here that way instead.

Can I use the 3.x shell for 2.x?

Sure, with a trick. See use-3-x-migrations-for-your-2-x-cakephp-app on how to provide 3.x shell access and access to my Tools and Setup shells even for 2.x apps.

Tips

If you have a larger database and tables > 1GB you definitely want to put the site into maintenance mode and do this during the night or a very inactive time-frame, as it will need quite a few minutes to complete.

It will also increase your DB size, in my case from 2.1 to 2.5 GB. But that is worth it if it does not silently truncate data anymore.

Or just use Postgres

It turns out that Postgres natively supports emoji and alike, without any need for mb4 modification.
So maybe, if you still use MySQL it could also be time to switch

Further links

5.00 avg. rating (93% score) - 1 vote
 
No Comments

Posted by Mark in CakePHP, MySQL

 

CakePHP and connecting to GitHub API

22 Oct

I had to write a small tool to automate releasing certain GitHub repositories, and for that to authenticate I had to connect to GitHub API.
The integration wasn’t super-easy as there was no documentation yet on how this could be done. But I finally figured it out and want to share it.

HybridAuth plugin

I first introduce the plugin pretty quick I chose to use as authentication piece.
HybridAuth is maintained by a CakePHP core developer and bridges the original HybridAuth implementation into CakePHP. That library aims to "act as an abstract API between your application and various social APIs and identities providers". Out of the box it provides quite a few very popular services to connect to.

Getting started

I did install the plugin as documented, I also made sure the Migration file for it has been included because
we do need a "social_profiles" table here.

Then I connected the Users and SocialProfiles table:

    /**
     * @param array $config The configuration for the Table.
     *
     * @return void
     */
    public function initialize(array $config) {
        parent::initialize($config);
        ...
        $this->hasMany('ADmad/HybridAuth.SocialProfiles');
        EventManager::instance()->on('HybridAuth.newUser', [$this, 'createUser']);
    }
    /**
     * @param \Cake\Event\Event $event
     *
     * @throws \RuntimeException
     *
     * @return \App\Model\Entity\User
     */
    public function createUser(Event $event) {
        // Entity representing record in social_profiles table
        $profile = $event->data()['profile'];
        $username = substr($profile->profile_url, strrpos($profile->profile_url, '/') + 1);
        $user = $this->newEntity(
            [
                'username' => $username,
                'email' => $profile->email
            ]
        );
        $result = $this->save($user);
        if (!$result) {
            throw new \RuntimeException('Unable to save new user:' . print_r($user->errors(), true));
        }
        return $result;
    }

I used the "profile_url" data to automatically generate the same user on my website.
Since the login was only allowed via GitHub login, there was no change of collision.

Then I made sure the HybridAuth authentication adapter is added to the list of components in the AppController:

    /*
     * @return \Cake\Network\Response|null|void
     */
    public function initialize() {
        parent::initialize();
        ...
        $this->loadComponent('TinyAuth.Auth', [
            'authenticate' => [
                'Form',
                'ADmad/HybridAuth.HybridAuth',
            ],
        ]);
    }

I also modified the login according to the documentation.

And finally I just needed a link in the navigation menu in the case the user is not logged in yet:

echo $this->Html->link(
    'Login with GitHub',
    ['plugin' => false, 'prefix' => false, 'controller' => 'Account', 'action' => 'login', 
        '?' => ['provider' => 'Github', 'redirect' => $this->request->query('redirect')]
    ]
);

Note that the "redirect" query string is only necessary for CakePHP 3.4+ when the session is not used anymore for remembering the location to redirect to after login. And also note that at this point only a "dev" branch of the plugin supports the 3.4+ version yet.

Figuring out the configuration

Now that was the most difficult part. With a lot of debugging I found out that since the GitHub provider is not one of the core ones I need to provider wrapper path and class here:

    'HybridAuth' => [
        'providers' => [
            'Github' => [
                'enabled' => true,
                'keys' => [
                    'id' => env('AUTH_ID_GITHUB', ''),
                    'secret' => env('AUTH_SECRET_GITHUB', '')
                ],
                'wrapper' => [
                    'path' => ROOT . '/vendor/hybridauth/hybridauth/additional-providers/hybridauth-github/Providers/GitHub.php',
                    'class' => 'Hybrid_Providers_GitHub'
                ],
                'scope' => 'user:email,repo'
            ]
        ],
        'debug_mode' => false,
        'debug_file' => LOGS . 'hybridauth.log',
    ],

Note that I also set custom "scope" permissions here, you can however here leave that out or add more.

Small tweaks

I didn’t want to use the the plugin controller action to authenticate, but my own in AccountController (in order to execute a few custom things upon login).
So I just overwrote the hauth_return_toURL:

'hauth_return_to' => [
	'controller' => 'Account', 'action' => 'authenticated', 'plugin' => false, 'prefix' => false
]

Testing

Yeah, ok, here I did cheat.
The hybridauth library has a little flaw that makes it difficult to connect to CakePHP as plugin: It always forces the session to be started right away. Especially when testing the controllers now this can be super annoying as it throws ugly warnings:

..Warning Error: session_start(): Cannot send session cookie - headers already sent by 
(output started at phar:///home/vagrant/Apps/.../phpunit.phar/phpunit/Util/Printer.php:134) 
in [/home/vagrant/Apps/.../vendor/hybridauth/hybridauth/hybridauth/Hybrid/Storage.php, line 20]

So I just added the adapter when not in CLI mode:

if (PHP_SAPI !== 'cli') {
	$authenticate['ADmad/HybridAuth.HybridAuth'] = [
		...
	];
}
$this->Auth->config('authenticate', $authenticate);

Tests are green again πŸ™‚

In short

All in all HybridAuth is a great CakePHP plugin to connect this HybridAuth library and any OpenID and OAuth authenticated service to your application.
Give it a spin!

Besides the here mentioned GitHub provider I also managed to use Facebook/Google sign-in this way in another app.
Basically all apps, if for technical users or more a social network, can benefit from such a one-click login as it really takes away the pain of double-opt-in registration forms and alike.

1.00 avg. rating (53% score) - 1 vote
 
No Comments

Posted by Mark in CakePHP

 

CakePHP Tips Fall 2016

18 Oct

Always use proper version check method

Be aware of version checks that are using the inferior and even wrong </> comparison.
This can lead to wrong conditions with higher minor versions.

I had this in my code from the early 2.x days:

if ((float)Configure::version() < 2.4) {
    ...
}

With the upcoming 2.10 release this will now suddenly start to return true. Luckily my 2.next tests already revealed that and I was able to fix it up properly:

if (version_compare(Configure::version(), '2.4') < 0) {
    ...
}

This will now work in all minors of 2.x.

The same is true for 3.x, of course, even though we are "only" at 3.3.6 at this point in time yet.

Order your flash messages semantically

You can use the Flash plugin to enhance your flash messages a bit.
It works out of the box with your current setup, but adds a few useful things on top:

  • Prevent size and output issues when running into a redirect loop boiling up messages in the session (>> 50) by limiting the stack to 10 by default.
  • Use ordered output (error first, then warning, success and lastly info). Errors should be visible first in case multiple types are to be displayed.

Switch away from basic log files

I would switch away from basic log files to database – even if it is just a simple SQLite one like DebugKit uses.
This way you can more easily navigate and filter through them.
Check out the DatabaseLog plugin which can do exactly that in just a few minutes of configuration.
For not just personal fun apps it is advised to look into a bit more sophisticated approaches, like using Monolog and services like NewRelic to write to. But for smaller projects it can be enough to have a small admin backend to filter through the logs, especially error and warning types.

Keep your controller code lean

That specifically includes all those verbose allow statements to make certain pages public:

use Cake\Event\Event; 
...
 	/**
	 * @return void
	 */
	public function beforeFilter(Event $event) {
		parent::beforeFilter($event);
		$this->Auth->allow('index');
	}

See TinyAuth which since recently allows to more cleanly declare this with a single INI file in your src/config folder.
The complete code above goes away for every controller πŸ™‚

As long as not needed (custom dynamically made decisions based on session or alike) this kind of noise should be kept out of the controllers.
This makes it also possible to modify the public access to actions without the need to be a developer. The next step could be to make the input for TinyAuth database-driven and alike.

0.00 avg. rating (0% score) - 0 votes
 
No Comments

Posted by Mark in CakePHP

 

Use 3.x Migrations for your 2.x CakePHP app

03 Oct

In this post I reveal one of my tricks on how to leverage 3.x power in a legacy 2.x project.

You might have already read on how to use some of the splits, like the ORM, in 2.x projects.
Today I want to talk about migration as a topic.

Status Quo

I do have to maintain two remaining CakePHP 2.x apps that have been too large to just upgrade yet.
And time and budget was not on my side so far.
In 2.x there was also not a real powerful database migration tool available so far.

Let’s use the 3.x Migrations plugin

We can use the Migrations plugin quite easily in all 2.x apps do all database modification this way.

First we create a subfolder in your 2.x root folder, let’s call it /upgrade.
This will contain a standalone 3.x app including the Migrations plugin as dependency.
In my case the composer.json looks like this:

	"require": {
		"cakephp/cakephp": "^3.3",
		"cakephp/migrations": "^1.6",
		"dereuromark/cakephp-setup": "^1.0",
		"dereuromark/cakephp-tools": "^1.1"
	},
	"require-dev": {
		"cakephp/bake": "^1.2",
		"cakephp/debug_kit": "^3.2"
	},

Since I include cakephp/bake, I can also leverage the Bake plugin to generate the necessary migration file.

Any time I need a new migration file I simply go to the subfolder and use the 3.x shell:

cd upgrade
bin/cake bake migration CreateArticles ...

Of course you can now modify it further and once complete commit this file into version control.

On the server your deployment script just also needs to contain the following lines then to fully automate it:

cd upgrade
composer install --prefer-dist --no-dev --optimize-autoloader --no-interaction
chmod +x bin/cake
bin/cake Migrations migrate
cd ..

Once you upgrade to 3.x you can move all migration files to the actual place in your app, remove the subfolder and simplify the deployment lines to just the single command πŸ™‚

At least I now have to only remember one way to do migrations, for all 3.x and the old 2.x apps. And I can benefit from all recent improvements in those plugins even in those old apps.

Upgrading from existing 2.x migration tool?

You might be using a 2.x tool like this already, but upgrading to the state of the art 3.x Migrations plugin hotness is not a problem here, either.

Just create a dump of the current schema, put it into an SQL file and include that in your first Migrations file:

public function change() {
	$sql = file_get_contents('dump.sql');
	$this->query($sql);
}

Make sure you mark it as migrated, so it is not accidentally executed again.
As alternative you could build in a switch to auto-detect if one of the tables already exists:

$exists = $this->hasTable('users');
if ($exists) {
	return;
}
...

Tips

Deploy admin user along with the schema

In some cases it can make sense to provide a basic admin login along with the first initial migration:

$data = [
	[
		'username' => 'admin',
		'email' => 'admin@example.com',
		'password' => '...' // Must be changed right afterwards
	]
];
$table = $this->table('users');
$table->insert($data)->save();

For more, it is advised to leverage the seed functionality the Migrations plugin ships with.

Further goodies

As you can see, I also included my Setup and Tools plugin, which in v3 also contain very useful and powerful tools for database maintenance and alike. I can now also leverage them and do not have to backport everything to 2.x anymore.
The same would be true for any such plugin and will help you save time for other things if you can focus on development for the 3.x branch only.

Bottom line

Every pre-3.x project should definitly have a subfolder which runs an up-to-date CakePHP 3.x shell including all useful and required plugin shells.

Feel free to share your ideas and experiences on advancing slowly towards 3.x as comments.
See my old post about it for some more details on how to share the credentials, so you can keep them DRY in your main app config.

0.00 avg. rating (0% score) - 0 votes
 
No Comments

Posted by Mark in CakePHP

 

Chronos – Let there be time

12 Aug

In PHP most know of DateTime class to handle date and time.
At least with more modern PHP versions it is now not advised anymore to use the plain old date() and time() functions.

The use cases – especially with a more global world – these days more often include correct time zone handling as well as more robust
delta handling. But using objects also means you have to be more careful about (accidentally) modifying the original date when you are creating a new one from it.

Until now the de-facto standard pretty much was Carbon – as we all know.
It wrapped the DateTime object and applied some necessary bugfixes as well as a lot of useful enhancements like better object oriented access for reading and writing.

We at CakePHP also wanted to start using it, faced quite a few issues though at the time.
One was, that it seemed unmaintained over months of time – often times with critical or at least major bugs not being fixed.
There was also the problem that there was no (and still not is) fork or version for a more modern PHP 5.4+ approach. We actually wanted and needed PHP 5.5+ support due to a lot of necessary enhancements of date time handling in PHP, more to that later.
So even after approaching them multiple times, trying to offer a helping hand here, not much changed.

The solution for us then was the only viable one on the table: We need to create a clone of it, and start maintaining it ourselves.
Chronos as modern and future proof stand-alone library to handle date and (date)time.
As a side-effect we were able to also implement better interfaces around it and could leverage all the new PHP features.

And as of this week, the Chronos library is officially marked as stable 1.0.0 πŸ™‚

Main differences and improvements

  • Implements ChronosInterface for proper typehinting, e.g. in methods
  • DateTime and Date (no time) handling separately per use case
  • Immutable by default for cleaner coding and less errors
  • Correct some faulty standards (ISO code violations) and behavior (difference calculation)
  • No external dependencies

Mutable vs Immutable

That topic is present throughout many layers of data handling, but with objects being passed around by reference, this is especially important around
data manipulation inside your business layer.
Using mutable by default means that you could easily modify a DateTime object (or Chronos in this case maybe) by accident.
You could have added a day to check if that following one is still a weekday, but at the same time this modification than accidentally back out of the method and down the chain of method invocations. The next method then uses the altered datetime and so on and so on.

// Bad practice - and doesn't work with immutable objects
$datetime->addDay(1);
$this->doSomething($datetime);
return $datetime;
// Better to never touch the original object - this works like you'd expect
$datetime = $datetime->addDay(1);
$datetime = $this->doSomething($datetime);
return $datetime;

Shimming buggy PHP core behavior

Intuitively, if you add months instead of specific days to a date, you would expect this to be "month-exact", not "day-exact".

$dt = new DateTime('2015-01-31');
$dt->modify("+1 month");
echo $dt->format("Y-m-d H:i:s");   //2015-03-03 00:00:00

Clearly, this overflows in unexpected ways.

So Chronos actually gives you addMonths()/subMonths() that actually work as desired:

$dt = new Chronos('2015-01-31');
$dt = $dt->addMonths(1);
echo $dt->format("Y-m-d H:i:s");   //2015-02-28 00:00:00

To get the former PHP behavior back, you can explicitly use addMonthsWithOverflow()/subMonthsWithOverflow() methods. Not that is is ever useful or recommended πŸ™‚

Testing and fixating time

Everyone knows those one second issues when writing tests and (date)time. Sometimes tests fail because the time for now() jumped to the next second.

When writing unit tests, it is helpful to fixate the current time. Chronos lets you fix the current time for each class. As part of your test suite’s bootstrap process you can include the following:

Chronos::setTestNow(Chronos::now());
MutableDateTime::setTestNow(MutableDateTime::now());
Date::setTestNow(Date::now());
MutableDate::setTestNow(MutableDate::now());

This will fix the current time of all objects to be the point at which the test suite started.

Usage

The Chronos API offers a very fast and intuitive way to work with datetime.

Let’s say you want to find the next Tuesday, if the current one is not already one:

$dt = new Chronos('2015-01-31');
if (!$dt->isTuesday()) {
    $dt = $dt->next(ChronosInterface::TUESDAY);
}

Quite convenient are also the checks to find out whether a date is in the past or the future:

$dt->isPast();
$dt->isFuture();

Of course, you could also use a more verbose way with gt()/lt() and a current "now" datetime.

Check out the official chronos docs for how to use it in general.

Usage in frameworks

Usually, frameworks should be able to switch inside DB layer from DateTime or Carbon to Chronos easily.
In CakePHP for example the type conversation is setup in the bootstrap, and it already uses the immutable Chronos objects by default:

// bootstrap.php
/**
 * Enable immutable time objects in the ORM.
 *
 * You can enable default locale format parsing by adding calls
 * to `useLocaleParser()`. This enables the automatic conversion of
 * locale specific date formats. For details see
 * @link http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data
 */
Type::build('time')
    ->useImmutable();
Type::build('date')
    ->useImmutable();
Type::build('datetime')
    ->useImmutable();

The underlying classes here extend Carbon and so in the ORM all ingoing and outgoing datetimes are Chronos objects.

5.00 avg. rating (95% score) - 2 votes
 
No Comments

Posted by Mark in PHP

 

Use isset() and empty() wisely

01 Jun

This is another part of the series "How to write better PHP code".

Sometimes it is the small things than can make all the difference. In this case simply using the correct way of checking
for variable content can avoid quite a few bugs in the long run.

What is the issue here

Very often people abuse empty()/!empty() and isset()/!isset() where they shouldn’t. I have seen this in many frameworks,
and in retrospective also in my own code for quite some time.

The main problem is that it does two things at the same time:

  • Checks if that variable exists at this point in time, if not silently bail early
  • If it exists it also checks of the content is not empty or set

Now, that sounds like "so who cares" – but it in fact has quite some impact in the correctness of code, especially when refactoring is involved.

Concrete issue

There was an actual bug in the CakePHP framework because of this.
The class attribute $compiledRoute was renamed, but a single use of that one was checked with !empty(), so that part of the code inside this check became unreachable and dead forever. Since this one piece of code didn’t have a test for it, it also remained dormant for a very long time.

Buggy behavior with methods

Since PHP 5.5+ it is now even possible to check expressions and more, so !empty($this->foo()) would be possible.
This should never be used though as this can have side-effects depending on the implementation of the class and is absolutely not necessary.

So what to do

The basic rule is: Always prefer non-silent checks.
Also always try to compare with === checks and expect the variable or attribute to be declared at run-time.

Only ever use empty()/isset() if that is not possible, that means if there is a chance that the variable or attribute could be not set at this point in time.
Same goes for array keys and alike.
But for variables and attributes you might want to ask yourself it that is maybe not a code smell after all if you do not know that for certain.

Luckily IDEs these days provide a lot more help than a few years ago, but there is still lot of room for error.
Let’s look into more concrete examples now.

Examples

Method arguments

public function read($key, $context = null) {
    ...
    if (!empty($context)) {
        // Do something
    }
    ...
}

What happens now if you refactor $context in the signature, but forget the one inside the if check?
Using this approach would have 100% identical behavior while making sure you couldn’t have forgotten it:

public function read($key, $context = null) {
    ...
    if ($context) {
        // Do something
    }
    ...
}

Ideally you would also look into more strict checks if applicable, but this is already way better than before.

Class attributes

protected $foo;
public function read($key) {
    ...
    if (isset($this->fooo)) { // Notice the typo
        // Do something (oh no, this will never happen now)
    }
    ...
}

While coding, we made a typo and never notice it. If you also don’t bother to write a test for this case, you might only discover it very late in the process, if at all.
So it should look like:

protected $foo;
public function read($key) {
    ...
    if ($this->foo !== null) {
        // Do something
    }
    ...
}

Renaming only one of the two would immediately trigger an error and the developer gets notified about his coding mistake.

Array keys

protected $config = [
    'recursive' => false
];
public function read($key) {
    ...
    if (!empty($this->config['recursive'])) {
        // Do something
    }
    ...
}

We can see that the key must exist. If not, we screwed up. So why using the wrong check that would only cloak spelling mistakes.

Better code like:

protected $config = [
    'recursive' => false
];
public function read($key) {
    ...
    if ($this->config['recursive']) {
        // Do something
    }
    ...
}

Optional array keys

public function read($key, array $options = []) {
    ...
    if (!empty($options['recursive'])) {
        // Do something
    }
    ...
}

In this particular case the recursive option is optional, thus the key could be empty here.
This would be OK.

One way to maybe improve this would be to merge the $options array with some $defaults which contain all required keys, then you can also use the proper non-cloaking checks again.

More examples

Don’t wrap methods, especially for "object or null" return values:

// Bad
if (!empty($this->getSomeObjectOrNull()) {}
// Good
if ($this->getSomeObjectOrNull() !== null) {}

I also often see the redundancy that makes no sense:

// Bad
if (isset($x) && !empty($x)) {}
// Identical (but maybe we also don't need the !empty here?)
if (!empty($x)) {}
// Better (maybe even strict checks?)
$x = null;
...
if ($x) {}

Usually variables should not just sometimes exist. Declare them as null first if you conditionally populate them somewhere.

Bear in mind here, that 0 and '0' would not work with either way and in that case you need to be strict in your checks anyway.
There also many buggy comparison cases around the 0 integer and a reason more to try to be more strict in general wherever possible.
That includes in_array() by the way, one of the functions probably most (framework and project) bugs have been discovered the last months due to this implicit casting issue leading to false positives.

Further reading

There was an RFC discussion in CakePHP around the same issue, as direct result of a bug that would never have been there if the above was applied properly.

Please share your thoughts on the topic as comments.

4.33 avg. rating (86% score) - 6 votes
 
No Comments

Posted by Mark in PHP