CakePHP 2023 Updates: Performance, Security and Testing

You maintain a CakePHP app that’s been running for a few years, and someone on your team asks whether it’s worth upgrading or time to move to another PHP framework. Before you answer, it helps to know what has actually changed. In this post I’ll walk you through the CakePHP updates for 2023 that matter most when you build and run real apps.

Faster CakePHP apps with better caching and queries

The 2023 CakePHP updates focus on making your apps faster and lighter on resources. Caching works better, database queries are more efficient, and the framework uses resources more carefully.

In practice, that means shorter response times and more headroom when traffic spikes. If you want to see the difference for yourself, I’d suggest putting some monitoring in place first. My guide on setting up Grafana with Docker Compose uses a Next.js app, but the same setup works for a PHP stack.

Support for newer PHP versions

CakePHP keeps up with the PHP community and now works with the most recent PHP versions. That gives you access to newer language features, speed improvements and security patches while you keep using CakePHP.

Moving your project to a current PHP version also helps with code quality and security. If your server is still on an old release, follow my walkthrough on upgrading PHP 7.4 to PHP 8.4 on Ubuntu before you bump the framework.

Add GraphQL to a CakePHP app

CakePHP 2023 adds support for GraphQL, so you can build flexible APIs without leaving the framework. GraphQL is a query language for APIs that lets the client ask for exactly the data it needs in a single request.

With GraphQL in place, you define a schema, handle queries and pull data from several sources through one endpoint. Here’s how to wire it up.

To send GraphQL requests to your app, add a route in your config/routes.php file:

use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::plugin('CakeGraphQL', ['path' => '/graphql'], function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Books', 'action' => 'index', '_method' => 'POST']);
});

This route points every GraphQL request to one controller action. Make sure the controller and action names match the ones you create next.

To run the query, create a controller action that handles the GraphQL request:

// BooksController.php

namespace App\Controller;

use Cake\Controller\Controller;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Error\DebugFlag;

class BooksController extends Controller
{
    public function index()
    {
        $query = $this->request->getData('query');

        // Create an instance of your GraphQL schema
        $schema = new Schema([
            'query' => $this->buildSchema(),
        ]);

        // Execute the GraphQL query
        $result = GraphQL::executeQuery($schema, $query)->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE);

        $this->set([
            '_serialize' => ['result'],
            'result' => $result,
        ]);
    }

    private function buildSchema()
    {
        // Build and return your GraphQL schema object
        // You can use a library like 'webonyx/graphql-php' to define types, fields, and resolvers programmatically
        // Refer to the documentation for detailed instructions on building the schema
    }
}

Send a test query to the endpoint and check that you get JSON back. If you get a 404, the route and the action name usually don’t match.

Clearer error messages and debugging in CakePHP

The latest CakePHP release improves built-in error handling with more detailed error messages, stack traces and debug information. You spend less time guessing where things broke and more time fixing them.

Catching bugs early during development also means fewer surprises once the app is live.

// src/Error/AppExceptionRenderer.php

namespace App\Error;

use Cake\Error\ExceptionRenderer;
use Cake\Http\Response;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Exception\BadRequestException;

class AppExceptionRenderer extends ExceptionRenderer
{
    public function render(): Response
    {
        $exception = $this->error;

        if ($exception instanceof NotFoundException) {
            // Handle 404 Not Found errors
            return $this->handleNotFoundException($exception);
        } elseif ($exception instanceof BadRequestException) {
            // Handle 400 Bad Request errors
            return $this->handleBadRequestException($exception);
        }

        // For other exceptions, fallback to the parent renderer
        return parent::render();
    }

    protected function handleNotFoundException(NotFoundException $exception): Response
    {
        $response = new Response();
        $response->statusCode(404);
        $response->type('json');
        $response->body(json_encode([
            'error' => [
                'message' => 'Resource not found.',
                'code' => 404,
            ],
        ]));

        return $response;
    }

    protected function handleBadRequestException(BadRequestException $exception): Response
    {
        $response = new Response();
        $response->statusCode(400);
        $response->type('json');
        $response->body(json_encode([
            'error' => [
                'message' => 'Bad request.',
                'code' => 400,
            ],
        ]));

        return $response;
    }
}

Simpler authentication and authorization

CakePHP 2023 makes authentication and authorization easier to set up. Authentication checks who a user is, and authorization decides what that user is allowed to do.

The framework now has better support for standard authentication protocols and a simpler way to handle role-based access control, where you give permissions to roles like “admin” or “editor” instead of to each user. You get solid security without writing it all from scratch.

Easier testing in CakePHP

CakePHP 2023 ships better testing tools and more complete documentation. Writing unit, functional and integration tests takes less effort, so you’re more likely to actually write them.

Good tests let you check that your app behaves the way you expect and help you avoid regression bugs, those old bugs that sneak back in after a change.

Is CakePHP still worth it?

For PHP web apps, I’d say yes. Between the speed improvements, the security updates and the better testing tools, CakePHP is still a reliable and flexible choice.

For the full list of changes, read the CakePHP 4.4.0 release announcement on the Bakery. And once your app is ready to ship, my guide on deploying Nginx on Ubuntu with Ansible is a good next read.

Hope this helps you plan your next upgrade. 🍰


Leave a Reply