Middleware and CakePHP

22 Apr

I started to migrate some of my CakePHP 3.x apps to CakePHP 3.3 middleware and even tested 3.4 already back in 2016.
Until then I didn’t even try the new PSR7 way. But it was about time I caught up here.
I wanted to actually start using some of the Middleware classes available.

I also always wanted to dig deeper into this topic that hasn’t yet too much blog post coverage it seems.
Now, let’s get started here 1.5 years later – but with some very useful gotchas (later in the article more).

Middleware what?

Yeah, this new PSR7 thing – you can also read more about it here.
In fact, it is not that new, but more and more frameworks have been adopting, and so did CakePHP.
When you are upgrading from 3.3 to a newer minor version, you will stumble upon it.

There are also tons of middleware already available out there that – by design – is supposed to work with any PHP framework.
Check out this impressive list.

But now back to CakePHP 3.

First steps

So what to do first to get this new infrastructure working?
The docs explain it quite well:

  • You update your index.php with the new way of dispatching a request (see cakephp/app‘s index.php).
  • You copy and paste the Application.php skeleton into your src/ directory (App namespace). It should be the only class there.

Then you remove your current bootstrap lines around DispatcherFactory::add(...).
You now can add the same functionality as Middleware again in your Application class.

Hands on

Let’s show it with two of my new Middleware classes, "Maintenance" and the improved "ErrorHandler". The first will be an addition, the second one a replacement.

use Setup\Middleware\MaintenanceMiddleware;
use Tools\Error\Middleware\ErrorHandlerMiddleware;
class Application extends BaseApplication {
	 * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
	 * @return \Cake\Http\MiddlewareQueue The updated middleware.
	public function middleware($middlewareQueue) {
			// Add Setup plugin Maintenance middleware
			// Improved Tools plugin ErrorHandler middleware
			// Handle plugin/theme assets like CakePHP normally does.
			// Finally apply normal routing
		return $middlewareQueue;

Instead of the ::class way you could also instantiate the classes: new ...Middleware().
But I prefer to keep them strings only until used, especially since I don’t need to pass any arguments for them.

When to use, and when not to use.

The middleware opens a few new possibilities, but it can also introduce more bad code.
You should decide wisely, what can/should be transformed into a middleware class.

Useful cases are usually:

  • Basic low level caching.
  • Serving assets (e.g. a custom WYSIWYG editor serving).
  • Manipulating the request early on, or the response afterwards.
  • Authentication and header parsing, e.g. Token based ones
  • Needing a very early on decision point on certain dispatching options.

You should be careful about:

  • Templating/Rending involved, here usually it is better to use controller (+component?) and normal view rendering.
  • Needing more customization on a controller level, on what parts of the app invoke this logic and which don’t (usually can stay an easy to hook in component).

Now to the gotchas I promised:

Why the improved ErrorHandler?

The core one treats all errors the same by default. Even user-triggered "out of bounds" or not found records are logged into the "error" log.
I find that totally wrong – and even harmful – as it cloaks the actual "internal errors" of higher severity.
So the improved handler provides a way to whitelist certain exceptions as "404" ones that can be triggered from visitors or bots and do not represent internal application errors. It uses the referer to decide whether this is "404" (externally triggered), or an actual issue for error.log (internal reference).
This 404.log then can be occasionally checked and removed, while the error.log as such has to be more closely monitored and everything coming in should be fixed ASAP.

More about the implementation details in the Setup plugin docs.
It is important to also switch out the low level handler in your bootstrap here as well as setting up a specific 404 listener.

Tip: If you use DatabaseLog plugin, you can easily set up a monitoring cronjob to alert the admin (e.g. via email) within seconds of severe issues/errors. With the above "separation" you don’t have false positives and will get only "real" alerts. The plugin built in alert system also makes sure errors are batch-sent to not send out too much emails. Of course you can also limit the scope of alerts further to e.g. only very severe exceptions using the configuration.

Maintenance, what’s that about?

I use this to put the whole application into maintenance mode if there is a more time intensive deployment coming up to assert the users don’t upload images during that timeframe, or put something into the database while it migrates which then breaks.
Usually it is only a few seconds – but it helps to keep the integraty of the website intact.

See my blog post about it, also check the Setup plugin documentation.

The best use case is adding those two commands (enable, disable) into your deploy script, at the beginning and the end. But you can also invoke it through command line manually, when you plan on doing some larger migration or maintenance work.

Other useful middlewares

(Browser) Language detection

The I18n middleware sounds useful if you need to provide multi-locale output and want to detect the best default.
The old approach would have been a component, the more modern way is a middleware here then, for example.


The Throttle middleware can be used for certain (API) requests to stay under a certain limit of requests per timeframe.

Your recommendations?

You can comment with your recommended middleware classes, CakePHP or otherwise.

4.00 avg. rating (83% score) - 1 vote
No Comments

Posted by Mark in CakePHP


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:


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:" 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 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.


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": ""

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:

    - php: 5.6
      env: PREFER_LOWEST=1

Then exchange the first before_script line composer install with

  - 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.


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:

    - php: 7.0
      env: PHPSTAN=1 DEFAULT=0
  - 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:

        	- %rootDir%/../../../tests/bootstrap.php
		- %rootDir%/../../../src/TestSuite/*
		- '#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

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": "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@"

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@
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

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.


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.


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) {
        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() {
        $this->loadComponent('TinyAuth.Auth', [
            'authenticate' => [

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


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 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) {

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');

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) {


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' => '',
		'password' => '...' // Must be changed right afterwards
$table = $this->table('users');

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
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:


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


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:


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

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