Review of CakePHP 3: Still Fresh, Still Hot

In the past month, the CakePHP team released the alpha version of CakePHP 3. This version is considered a significant advancement by the Cake development team. With the alpha release now available, this article reexamines CakePHP 3 as a powerful and modern framework for PHP development.

This CakePHP 3 treat is fresh out of the oven.

A Short History

PHP development today offers numerous options. As PHP matured, a multitude of PHP frameworks emerged, providing developers with a vast selection. However, this wasn’t always the case.

Back in 2005, during the era of PHP 4, PHP frameworks were nonexistent. Implementing object-oriented programming in PHP was a significant hurdle. It was during this time that CakePHP, the pioneering PHP MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) framework, came into existence. Over nearly a decade since its initial release, CakePHP has continually evolved, maintaining a substantial share of the PHP developer market.

CakePHP’s popularity is evident in its ranking among the top 4 most popular PHP projects on GitHub, out of approximately 130,000. It boasts a thriving community with over 18,000 members in its Google group and 32,000 discussion topics. The framework’s collaborative nature is apparent with 270 code contributors and 320 documentation contributors. James Watts, a core team member and community manager of CakePHP for the Cake Software Foundation, whom I interviewed for this article, effectively summarizes CakePHP’s widespread and expanding popularity.

The release of version 3 positions CakePHP to maintain its leading role in the PHP ecosystem, competing strongly among today’s diverse range of PHP frameworks.

What’s New in CakePHP Version 3?

This evaluation is based on the alpha release of CakePHP 3.0, which introduces several new features and improvements, including:

  • Performance enhancements. Version 3 optimizes performance in the bootstrap process, routing, and various aspects of helper template generation.

  • Component and helper upgrades. Version 3 improves “flash message” support with its new FlashHelper and FlashComponent. The CookieComponent has been enhanced for easier separation of cookie namespace configuration and cookie data management.

  • Enhanced session handling. Previous versions’ static class-based session management presented challenges. Version 3 enables session access from the request object $this->request->session(), simplifying testing and allowing CakePHP to utilize PHPUnit 4.x.

  • Increased convention consistency. The application and plugin skeletons now share a unified directory structure, enhancing consistency.

  • Theme and plugin unification. To bolster themes, version 3 allows any plugin to function as a theme, simplifying packaging and distribution.

  • ORM Enhancements. Version 3 introduces several API changes to the ORM (Object-relational mapping), simplifying deep association specification for saving and modifying conventions to reduce the learning curve for new users.

Furthermore, additional features are planned for the beta release, notably:

  • Internationalization and localization (i18n and L10n) enhancements
  • An Edge Side Includes-based replacement for CacheHelper
  • A streamlined routing API for simpler and faster route declarations

Version 3 marks a significant advancement over previous CakePHP iterations.

Why Choose CakePHP?

CakePHP boasts numerous strengths, but this review highlights a few key differentiators:

Convention over Configuration

CakePHP prioritizes rapid and consistent development through a strong emphasis on convention. Similar to Ruby on Rails (a major source of inspiration for CakePHP), CakePHP strongly adheres to the convention over configuration principle.

Conventions eliminate the need for developers to ponder the organization of code while learning the framework, as default rules are already in place. Once mastered, these conventions allow developers to focus on core development tasks instead of code placement and configuration issues.

This emphasis on convention contrasts with PHP’s inherent flexibility. Consequently, CakePHP promotes coding style and structure consistency across developers and teams, fostering a standardized approach to development.

For instance, in database schemas, CakePHP employs default conventions for variable, table, and field naming. CakePHP expects:

  • Plural table names (e.g., orders)
  • Primary key fields named id
  • Foreign key fields named after the referenced table followed by _id (e.g., customer_id for a customers table reference).

To illustrate, let’s examine two tables from a blog post database: articles and users. In this scenario, an Articles “BelongsTo” a Users, and a Users “HasMany” Articles. CakePHP 3.0 represents these relationships as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
In ArticlesTable.php:
    class ArticlesTable extends Table {
        public function initialize(array $config) {
            $this->belongsTo('Users');
        }
   }

In UsersTable.php:
    class UsersTable extends Table {
        public function initialize(array $config) {
            $this->hasMany('Articles');
        }
    }

CakePHP automatically deduces foreign keys (e.g., user_id in the articles table) when fetching associations based on its default conventions.

Importantly, CakePHP 3 allows easy overriding of these conventions. For example, if the foreign key in the users table was author_id instead of user_id, two minor code adjustments would suffice:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
In ArticlesTable.php:
    class ArticlesTable extends Table {
        public function initialize(array $config) {
            $this->belongsTo('Users' => ['foreignKey' => 'author_id']);
        }
   }

In UsersTable.php:
    class UsersTable extends Table {
        public function initialize(array $config) {
            $this->hasMany('Articles' => ['foreignKey' => 'author_id']);
        }
    }

While integral to CakePHP, conventions can be easily overridden when necessary.

Although some developers prefer frameworks like Yii](http://www.yiiframework.com/) and Laravel with less reliance on conventions, CakePHP’s conventions offer significant advantages. They streamline the learning curve for developers working with existing codebases, as consistent coding structures and conventions are enforced across projects and developers.

CakePHP’s Object-relational Mapping (ORM)

CakePHP’s Object-relational mapping (ORM) benefits significantly from the framework’s conventions. By adhering to CakePHP’s database schema standards, developers can quickly link tables using the robust ORM. This eliminates the need for manual SQL statements in most cases, as CakePHP effortlessly handles tasks like table joins, hasMany, and even hasAndBelongsToMany relationships.

CakePHP’s ContainableBehavior enables developers to define SQL query selections for database tables and fields through model associations. This can span multiple tables, allowing for the construction of intricate SQL statements with ease.

CakePHP’s ContainableBehavior exemplifies the framework’s ability to simplify and optimize PHP development. It provides a clean and consistent method for data searching and filtering, enhancing application speed and overall performance. This is achieved by temporarily or permanently modifying model associations based on provided containments, generating a series of bindModel and unbindModel calls.

However, the ORM’s ease of use can lead to unintentionally inefficient SQL queries if developers are not cautious. I’ve encountered poorly written Cake applications with unoptimized queries that surface as performance bottlenecks as databases grow.

Prior to CakePHP 3, the ORM would retrieve all associated tables by default during queries. A simple “find all” query could become resource-intensive due to the retrieval of data from all related tables. Version 3 changes this default behavior. (In earlier versions, this behavior could be disabled by adding public $recursive = -1; to the main AppModel.php file.)

In summary, CakePHP’s ORM significantly streamlines development. When utilized correctly, it serves as a powerful tool for rapidly building complex queries. However, developers must thoroughly understand the ORM and ensure query optimization (as with any language).

Components and Helpers: CakePHP Libraries

CakePHP’s built-in libraries, Components and Helpers, are a valuable asset. They eliminate tedious and repetitive development tasks. In the MVC context, Components streamline controller development, while Helpers simplify view coding and presentation layer logic.

For instance, the PaginatorComponent automatically generates a next/previous page interface from a find query. Combining it with the JsHelper instantly enables AJAX Pagination powered by your preferred JavaScript framework (jQuery by default).

Other notable Helpers include:

  • TimeHelper: Provides numerous functions for formatting and manipulating time values, simplifying date and time display.
  • NumberHelper: Offers convenient methods for displaying numbers in various common (or custom) formats and precisions.
  • TextHelper: Assists in enabling links, formatting URLs, creating text excerpts, highlighting keywords, and gracefully truncating long text strings.

And many many more.

Criticisms of CakePHP 3

Every framework has its strengths and weaknesses, and CakePHP is no exception. Common criticisms include:

  • “Legacy framework; bloated and slow.” This criticism stems from CakePHP’s historical support for PHP versions as old as PHP 4. However, with PHP’s maturation and the release of CakePHP 3, this claim holds less weight.

  • “Overly strict and confining.” While advantageous, CakePHP’s conventions face criticism for being too rigid. Critics often overlook the ease with which these conventions can be overridden. CakePHP’s emphasis on standardization enhances consistency in PHP’s otherwise flexible coding practices.

  • “Slow release cycle.” A slower, more deliberate release cycle can be beneficial. CakePHP prioritizes backward compatibility with older PHP versions, resulting in fewer code changes for developers with new releases. The CakePHP 3 team maintains a monthly release schedule for minor releases (bug fixes, patches, minor enhancements) and typically addresses bug tickets within hours.

  • “Not an out-of-the-box solution.” Unlike some modern PHP frameworks that offer a complete out-of-the-box web app experience (like Yii), CakePHP focuses on supporting custom solutions. This has proven beneficial for developing large, customized, database-driven applications.

  • “Uses data arrays instead of objects.” This is no longer accurate in version 3. Previous versions relied on nested arrays for data storage and reference (e.g., $user['User']['username']). CakePHP 3 adopts object-based data storage (e.g., $user->username).

  • “Poor documentation.” While this criticism has some merit, the CakePHP development team acknowledges it and is actively working on improvements. The home page of the CakePHP 3 documentation emphasizes a commitment to documentation quality. As a community-driven project, CakePHP encourages user contributions to the documentation through an “Improve this Doc” button on every page.

Conclusion

Almost a decade after its initial release, CakePHP remains a strong and relevant competitor among PHP frameworks.

CakePHP provides a complete and comprehensive development solution with a mature codebase and extensive functionality. The framework’s primary focus on rapid development benefits both developers and stakeholders. By reducing development time, CakePHP minimizes a significant cost factor in software development.

As a community-driven project, CakePHP thrives on contributions. The launch of CakePHP 3, coupled with advancements in both PHP and the framework itself, ensures its continued growth and improvement.

If you’re seeking a PHP-based solution with similarities to Ruby on Rails in terms of user-friendliness and convention over configuration, consider trying CakePHP. The CakePHP Blog Tutorial](http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/blog.html) is quick to set up and explore. Alternatively, CakeCoded offers a structured series of lessons to familiarize PHP developers with CakePHP. These resources showcase how CakePHP can expedite and enhance your PHP development process. Enjoy!


Michael Houghton is a Toptal Engineer based in Ireland with extensive CakePHP expertise. He has developed over 100 websites using the framework, collaborated with CakeDC (the commercial entity behind CakePHP), contributed patches, and assisted with documentation.

Licensed under CC BY-NC-SA 4.0