CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Building Dynamic Web Applications with CakePHP and htmx: Advanced Features

This article is part of the CakeDC Advent Calendar 2024 (December 7th 2024)

This article continues our exploration of htmx integration with CakePHP, focusing on two powerful features that can significantly enhance user experience: inline editing and lazy loading of actions. These features demonstrate how htmx can transform traditional web interfaces into dynamic, responsive experiences while maintaining clean, maintainable code.

Other Articles in the Series

Inline Editing with htmx

Inline editing allows users to modify content directly on the page without navigating to separate edit forms. This pattern is particularly useful for content-heavy applications where users need to make quick updates to individual fields. With htmx, we can implement this feature with minimal JavaScript while maintaining a smooth, intuitive user experience.

Basic Implementation

The inline editing feature consists of three main components:

  1. A display view that shows the current value with an edit button
  2. An edit form that appears when the user clicks the edit button
  3. A controller action that handles both display and edit modes

Let's implement each component:

Controller Setup

First, we'll create a dedicated action in our controller to handle both viewing and editing states:

// /src/Controller/PostsController.php
public function inlineEdit(int $id, string $field)
{
    $post = $this->Posts->get($id, contain: []);
    $allowedFields = ['title', 'overview', 'body', 'is_published'];
    if (!in_array($field, $allowedFields)) {
        return $this->response->withStatus(403);
    }

    $mode = 'edit';
    if ($this->request->is(['post', 'put'])) {
        if ($this->request->getData('button') == 'cancel') {
            $mode = 'view';
        } else {
            $value = $this->request->getData($field);
            $post->set($field, $value);
            if ($this->Posts->save($post)) {
                $mode = 'view';
            }
        }
    }

    if ($this->getRequest()->is('htmx')) {
        $this->viewBuilder()->disableAutoLayout();
        $this->Htmx->setBlock('edit');
    }
    $this->set(compact('post', 'mode', 'field'));
}

View Helper

To maintain consistency and reduce code duplication, we'll create a helper to generate inline-editable fields:

// /src/View/Helper/HtmxWidgetsHelper.php
public function inlineEdit(string $field, $value, EntityInterface $entity): string
{
    $url = $this->Url->build([
        'action' => 'inlineEdit',
        $entity->get('id'),
        $field
    ]);
    return sprintf(
        '<div class="inline-edit-wrapper">
            <span class="field-value">%s</span>
            <button class="btn btn-sm inline-edit-btn" hx-get="%s">
                <i class="fas fa-edit"></i>
            </button>
        </div>',
        $value,
        $url
    );
}

Template Implementation

The template handles both view and edit modes:

// /templates/Posts/inline_edit.php
<?php
$formOptions = [
    'id' => 'posts',
    'hx-put' => $this->Url->build([
        'action' => 'inlineEdit',
        $post->id,
        $field,
    ]),
    'hx-target' => 'this',
    'hx-swap' => 'outerHTML',
    'class' => 'inline-edit-form inline-edit-wrapper',
];
?>
<?php $this->start('edit'); ?>
<?php if ($mode == 'view'): ?>
    <?php if ($field == 'is_published'): ?>
    <?= $this->HtmxWidgets->inlineEdit($field, $post->is_published ? 'Published' : 'Unpublished', $post); ?>
    <?php elseif ($field == 'body'): ?>
        <?= $this->HtmxWidgets->inlineEdit('body', $this->Text->autoParagraph(h($post->body)), $post) ?>
    <?php elseif ($field == 'overview'): ?>
        <?= $this->HtmxWidgets->inlineEdit('overview', $this->Text->autoParagraph(h($post->overview)), $post) ?>
    <?php else: ?>
        <?= $this->HtmxWidgets->inlineEdit($field, $post->get($field), $post); ?>
    <?php endif; ?>
<?php else: ?>
    <?= $this->Form->create($post, $formOptions) ?>
    <?= $this->Form->hidden('id'); ?>
    <?php if ($field == 'title'): ?>
        <?= $this->Form->control('title'); ?>
    <?php elseif ($field == 'overview'): ?>
        <?= $this->Form->control('overview'); ?>
    <?php elseif ($field == 'body'): ?>
        <?= $this->Form->control('body'); ?>
    <?php elseif ($field == 'is_published'): ?>
        <?= $this->Form->control('is_published'); ?>
    <?php endif; ?>
    <div class="inline-edit-actions">
        <?= $this->Form->button('<i class="fas fa-check"></i>', [
            'class' => 'btn btn-primary btn-sm inline-edit-trigger',
            'name' => 'button',
            'value' => 'save',
            'escapeTitle' => false,
        ]); ?>
        <?= $this->Form->button('<i class="fas fa-times"></i>', [
            'class' => 'btn btn-secondary btn-sm inline-edit-trigger',
            'name' => 'button',
            'value' => 'cancel',
            'escapeTitle' => false,
        ]); ?>
    </div>
    <?= $this->Form->end() ?>
<?php endif; ?>
<?php $this->end(); ?>
<?= $this->fetch('edit'); ?>

Styling

The CSS ensures a smooth transition between view and edit modes:

.inline-edit-wrapper {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}
.inline-edit-btn {
    padding: 0.25rem;
    background: none;
    border: none;
    cursor: pointer;
    opacity: 0.5;
}
.inline-edit-wrapper:hover .inline-edit-btn {
    opacity: 1;
}

.inline-edit-form {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.inline-edit-form .input {
    margin: 0;
}

.inline-edit-form input {
    padding: 0.25rem 0.5rem;
    height: auto;
    width: auto;
}

.inline-edit-actions {
    display: inline-flex;
    gap: 0.25rem;
}

.inline-edit-actions .btn {
    padding: 0.25rem 0.5rem;
    line-height: 1;
    height: auto;
}

.inline-edit-actions .btn {
    padding: 0.25rem;
    min-width: 24px;
    min-height: 24px;
}

.inline-edit-actions .btn[title]:hover::after {
    content: attr(title);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0,0,0,0.8);
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
}

Usage example

In the index template, we can use the helper to create inline-editable fields and provide a button to trigger the edit mode inside a table cell:

// /templates/Posts/index.php
<?= $this->HtmxWidgets->inlineEdit('title', $post->title, $post) ?>
<?= $this->HtmxWidgets->inlineEdit('is_published', $post->is_published ? __('Yes') : __('No'), $post) ?>

Inline Editing Flow

The inline editing feature transforms static content into interactive, editable fields directly on the page. This implementation follows a clear state-based workflow that provides immediate visual feedback while maintaining data integrity.

State Management

The system maintains two distinct states for each editable field:

  • View State: Displays the current value with an edit button
  • Edit State: Shows an editable form with save and cancel options

Workflow Steps

  1. Initial Display

    • Each editable field is wrapped in a container that includes both the value and an edit button
    • The edit button remains subtle until the user hovers over the field, providing a clean interface
    • The field's current value is displayed in a formatted, read-only view
  2. Entering Edit Mode

    • When the user clicks the edit button, htmx sends a GET request to fetch the edit form
    • The server determines the appropriate input type based on the field (text input, textarea, or checkbox)
    • The edit form smoothly replaces the static display
  3. Making Changes

    • Users can modify the field's value using the appropriate input control
    • The form provides clear save and cancel options
    • Visual feedback indicates the field is in edit mode
  4. Saving or Canceling

    • Saving triggers a PUT request with the updated value
    • The server validates and updates the field
    • If the value is invalid, the form is redisplayed with error messages
    • Canceling reverts to the view state without making changes
    • Both actions transition smoothly back to the view state that has been performed on success for edit and always on cancel

HTMX Attributes in Action

The implementation uses several key htmx attributes to manage the editing flow:

  1. View State Attributes

    • hx-get: Fetches the edit form when the edit button is clicked
    • hx-target: Ensures the form replaces the entire field container
    • hx-swap: Uses "outerHTML" to maintain proper DOM structure
  2. Edit State Attributes

    • hx-put: Submits the updated value to the server
    • hx-target: Targets the form container for replacement
    • hx-swap: Manages the transition back to view mode

Lazy Loading Actions

Lazy loading actions is a performance optimization technique where we defer loading action buttons until they're needed. This is particularly useful in tables or lists with many rows, where each row might have multiple actions that require permission checks or additional data loading.

Implementation

First, let's create a controller action to handle the lazy loading of actions:

// /src/Controller/PostsController.php
public function tableActions(int $id)
{
    $post = $this->Posts->get($id, contain: []);
    if ($this->getRequest()->is('htmx')) {
        $this->viewBuilder()->disableAutoLayout();
        $this->Htmx->setBlock('actions');
    }
    $this->set(compact('post'));
}

Table Actions Template

Create a reusable element for the action buttons:

// /templates/Posts/table_actions.php
<?php $this->start('actions'); ?>
<?= $this->Html->link(__('View'), ['action' => 'view', $post->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $post->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $post->id], ['confirm' => __('Are you sure you want to delete # {0}?', $post->id)]) ?>
<?php $this->end(); ?>
<?= $this->fetch('actions'); ?>

Template Element

Create a reusable element for the action buttons:

// /templates/element/lazy_actions.php
<div class="action-wrapper"
    hx-get="<?= $this->Url->build([
        'action' => 'tableActions',
        $entity->id,
    ]) ?>"
    hx-trigger="click"
    hx-swap="outerHTML"
    hx-target="this"
    hx-indicator="#spinner-<?= $entity->id ?>"
>
    <?= $this->Html->tag('button', '<i class="fas fa-ellipsis-vertical"></i>', [
        'class' => 'btn btn-light btn-sm rounded-circle',
        'type' => 'button'
    ]) ?>
    <div id="spinner-<?= $entity->id ?>" class="htmx-indicator" style="display: none;">
        <div class="spinner-border spinner-border-sm text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>
</div>

Usage in Tables

Implementation of the lazy loading trigger in your table rows is done by replacing the static actions with the lazy loading trigger:

The static actions is displayed as:

<!-- /templates/Posts/index.php -->
<td class="actions">
    <?= $this->Html->link(__('View'), ['action' => 'view', $post->id]) ?>
    <?= $this->Html->link(__('Edit'), ['action' => 'edit', $post->id]) ?>
    <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $post->id], ['confirm' => __('Are you sure you want to delete # {0}?', $post->id)]) ?>
</td>

And lazy loading trigger is displayed as:

<!-- /templates/Posts/index.php -->
<td class="actions">
    <?= $this->element('lazy_actions', ['entity' => $post]) ?>
</td>

Modal Forms and Views with htmx

Modal dialogs provide a focused way to present forms and content without navigating away from the current page. Using htmx, we can create dynamic modals that load their content asynchronously while maintaining a clean, maintainable codebase.

Implementation Overview

The modal implementation consists of several components:

  1. A modal container element in the default layout
  2. A dedicated modal layout for content
  3. A helper class for generating modal-triggering links
  4. JavaScript handlers for modal lifecycle events

Basic Setup

First, add the modal container to your default layout:

<!-- /templates/element/modal_container.php -->
<?php if (!$this->getRequest()->is('htmx')): ?>
<div id="modal-area"
    class="modal modal-blur fade"
    style="display: none"
    aria-hidden="false"
    tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content"></div>
    </div>
</div>
<script type="text/x-template" id="modal-loader">
    <div class="modal-body d-flex justify-content-center align-items-center" style="min-height: 200px;">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>
</script>
<?php endif; ?>

Modal Layout

Create a dedicated layout for modal content:

<!-- /templates/layout/modal.php -->
<?php
/**
 * Modal layout
 */
echo $this->fetch('css');
echo $this->fetch('script');

?>
<div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title"><?= $this->fetch('title') ?></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <?= $this->fetch('content') ?>
        </div>
    </div>
</div>

Modal Helper

Create a helper to generate modal-triggering links:

<?php
// /src/View/Helper/ModalHelper.php
declare(strict_types=1);

namespace App\View\Helper;

use Cake\View\Helper;

class ModalHelper extends Helper
{
    protected array $_defaultConfig = [
        'modalTarget' => '#modal-area',
    ];

    public array $helpers = ['Html', 'Url'];

    public function link(string $title, array|string $url, array $options = []): string
    {
        $defaultOptions = $this->getModalOptions($this->Url->build($url), 'get');
        $options = array_merge($defaultOptions, $options);

        return $this->Html->tag('a', $title, $options);
    }

    public function getModalOptions(string $url, string $method): array
    {
        $options = [
            'hx-target' => $this->getConfig('modalTarget'),
            'hx-trigger' => 'click',
            'hx-headers' => json_encode([
                'X-Modal-Request' => 'true',
            ]),
            'href' => 'javascript:void(0)',
            'data-bs-target' => $this->getConfig('modalTarget'),
        ];
        if (strtolower($method) === 'get') {
            $options['hx-get'] = $url;
        } else {
            $options['hx-' . strtolower($method)] = $url;
        }

        return $options;
    }
}

Controller Integration

Update your AppController to handle modal requests:

// /src/Controller/AppController.php
public function beforeRender(EventInterface $event)
{
    if ($this->isModalRequest()) {
        $this->viewBuilder()->setLayout('modal');
        $this->viewBuilder()->enableAutoLayout();
    }
}

protected function isModalRequest(): bool
{
    return $this->getRequest()->getHeader('X-Modal-Request') !== [];
}

JavaScript Integration

Add event handlers to manage modal behavior in your application's JavaScript:

// /webroot/js/app.js
document.addEventListener('htmx:beforeRequest', function(evt) {
    const target = evt.detail.target;
    if (target.id === 'modal-area') {
        const modalContent = document.querySelector('#modal-area .modal-content');
        if (modalContent) {
            modalContent.innerHTML = document.getElementById('modal-loader').innerHTML;
        }
        const modal = bootstrap.Modal.getInstance(target) || new bootstrap.Modal(target);
        modal.show();
    }
});

This handler ensures proper modal initialization and loading state display.

Usage Example

To create a modal-triggering link:

<!-- /templates/Posts/infinite.php -->
<?= $this->Modal->link(__('Edit'), ['action' => 'edit', $post->id]) ?>

Implementing Edit Form in Modal

Let's look at how to implement a complete edit form using modals. This requires changes to both the controller action and template.

Controller Action

Update the edit action to handle both regular and modal requests:

// /src/Controller/PostsController.php
public function edit($id = null)
{
    $post = $this->Posts->get($id, contain: []);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $post = $this->Posts->patchEntity($post, $this->request->getData());

        $success = $this->Posts->save($post);
        if ($success) {
            $message = __('The post has been saved.');
            $status = 'success';
        } else {
            $message = __('The post could not be saved. Please, try again.');
            $status = 'error';
        }
        $redirect = Router::url(['action' => 'index']);

        if ($this->getRequest()->is('htmx')) {
            if ($success) {
                $response = [
                    'messages' => [
                        ['message' => $message, 'status' => $status],
                    ],
                    'reload' => true,
                ];
                return $this->getResponse()
                    ->withType('json')
                    ->withHeader('X-Response-Type', 'json')
                    ->withStringBody(json_encode($response));
            }
        } else {
            $this->Flash->{$status}($message);
            if ($success) {
                return $this->redirect($redirect);
            }
        }
    }
    $this->set(compact('post'));
    if ($this->getRequest()->is('htmx')) {
        $this->Htmx->setBlock('post');
    }
}

Edit Form Template

Create a template that works both as a standalone page and within a modal:

<!-- /templates/Posts/edit.php -->
<?php
$this->assign('title', __('Edit Post'));
?>
<?php $this->start('post'); ?>
<div class="row">
    <div class="column-responsive column-80">
        <div class="posts form content">
            <?= $this->Form->create($post) ?>
            <fieldset>
                <?php
                    echo $this->Form->control('title');
                    echo $this->Form->control('body');
                    echo $this->Form->control('overview');
                    echo $this->Form->control('is_published');
                ?>
            </fieldset>
            <?= $this->Form->button(__('Submit')) ?>
            <?= $this->Form->end() ?>
        </div>
    </div>
</div>
<?php $this->end(); ?>
<?= $this->fetch('post'); ?>

The edit implementation seamlessly handles both modal and regular form submissions while maintaining consistent behavior across different request types. When validation errors occur, they are displayed directly within the modal, providing immediate feedback to users. Upon successful save, the page automatically refreshes to reflect the changes, and users receive feedback through toast notifications that appear in the corner of the screen.

The response processing on the client side follows the same pattern we explored in the previous article of this series.

Modal Workflow

Our modal implementation creates a smooth, intuitive user experience through several coordinated steps. During initial setup, we add the modal container to the default layout and initialize Bootstrap's modal component. A loading indicator template is also defined to provide visual feedback during content loading.

When a user clicks a modal-triggering link, HTMX sends a request with a special X-Modal-Request header. During this request, the loading indicator appears, giving users immediate feedback that their action is being processed.

The server recognizes the modal request through the special header and switches to the modal layout. This layout ensures content is properly formatted for display within the modal structure. As soon as the content is ready, the modal automatically appears on screen with a smooth animation.

For form submissions within the modal, HTMX handles the process using its attributes system. The server's response determines whether to update the modal's content (in case of validation errors) or close it (on successful submission). Throughout this process, toast notifications keep users informed of the operation's status, appearing briefly in the corner of the screen before automatically fading away.

Conclusion

Implementing inline editing and lazy loading actions with htmx in CakePHP demonstrates the framework's flexibility and htmx's power in creating dynamic interfaces. The combination allows developers to build modern, responsive features with minimal JavaScript while maintaining clean, maintainable code. CakePHP's built-in helpers and htmx's declarative approach work together seamlessly to create a superior user experience.

This article is the last one of the series of articles about htmx and CakePHP. We have covered a lot of ground and I hope you have learned something new and useful.

Demo Project for Article

The examples used in this article are located at https://github.com/skie/cakephp-htmx/tree/3.0.0 and available for testing.

This article is part of the CakeDC Advent Calendar 2024 (December 7th 2024)

Latest articles

CakeFest 2025 Wrap Up

For years I have heard the team talk about Madrid being one of their favorite cities to visit, because they hosted CakeFest there more than a decade ago. I can now confirm… they were right! What a beautiful city. Another great CakeFest in the books… Thanks Madrid!   Not only are we coming down from the sugar high, but we are also honored to be celebrating 20 years of CakePHP. It was amazing to celebrate with the attendees (both physical and virtual). If you watched the cake ceremony, you saw just how emotional it made Larry to reminisce on the last 20 years. I do know one thing, CakePHP would not be where it is without the dedicated core, and community.    Speaking of the core, we had both Mark Scherer and Mark Story joining us as presenters this year. It is a highlight for our team to interact with them each year. I know a lot of the other members from the core team would have liked to join us as well, but we hope to see them soon. The hard work they put in day after day is unmatched, and often not recognized enough. It’s hard to put into words how grateful we are for this group of bakers.    Our event was 2 jam packed days of workshops and talk presentations, which you can now see a replay of on our YouTube channel (youtube.com/cakephp). We had presenters from Canada, Germany, India, Spain, USA, and more! This is one of my favorite parts about the CakePHP community, the diversity and representation from all over the world. When we come together in one room, with one common goal, it’s just magical. Aside from the conference itself, the attendees had a chance to network, mingle, and enjoy meals together as a group.  I could sense the excitement of what’s to come for a framework that is very much still alive. Speaking of which… spoiler alert: CakePHP 6 is coming. Check out the roadmap HERE.   I feel as though our team leaves the event each year with a smile on their face, and looking forward to the next. The events are growing each year, although we do like to keep the small group/intimate type of atmosphere. I am already getting messages about the location for next year, and I promise we will let you know as soon as we can (when we know!). In the meantime, start preparing your talks, and send us your location votes.   The ovens are heating up….

Polymorphic Relationships in CakePHP: A Beginner's Guide

Have you ever wondered how to make one database table relate to multiple other tables? Imagine a comments table that needs to store comments for both articles and videos. How do you manage that without creating separate tables or complicated joins? The answer is a polymorphic relationship. It sounds fancy, but the idea is simple and super powerful.

What's a Polymorphic Relationship?

Think of it this way: instead of a single foreign key pointing to one specific table, a polymorphic relationship uses two columns to define the connection. Let's stick with our comments example. To link a comment to either an article or a video, your comments table would have these two special columns:
  1. foreign_id: This holds the ID of the related record (e.g., the id of an article or the id of a video).
  2. model_name: This stores the name of the model the comment belongs to (e.g., 'Articles' or 'Videos').
This flexible setup allows a single comment record to "morph" its relationship, pointing to different types of parent models. It's clean, efficient, and saves you from a lot of redundant code. It's not necessary for them to be called "foreign_id" and "model_name"; they could have other names (table, model, reference_key, model_id, etc.) as long as you maintain the intended function of each. Now, let's see how you can set this up in CakePHP 5 without breaking a sweat.

Making It Work in CakePHP 5

While some frameworks have built-in support for polymorphic relationships, CakePHP lets you create them just as easily using its powerful ORM (Object-Relational Mapper) associations. We'll use the conditions key to define the polymorphic link.

Step 1: Set Up Your Database

We'll use a simple schema with three tables: articles, videos, and comments. -- articles table CREATE TABLE articles ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) ); -- videos table CREATE TABLE videos ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) ); -- comments table CREATE TABLE comments ( id INT AUTO_INCREMENT PRIMARY KEY, content TEXT, foreign_id INT NOT NULL, model_name VARCHAR(50) NOT NULL ); Notice how the comments table has our special foreign_id and model_name columns.

Step 2: Configure Your Models in CakePHP

Now for the magic! We'll define the associations in our Table classes. ArticlesTable.php In this file, you'll tell the Articles model that it has many Comments, but with a specific condition. // src/Model/Table/ArticlesTable.php namespace App\Model\Table; use Cake\ORM\Table; class ArticlesTable extends Table { public function initialize(array $config): void { // ... $this->hasMany('Comments', [ 'foreignKey' => 'foreign_id', 'conditions' => ['Comments.model_name' => self::class], // or 'Articles' 'dependent' => true, // Deletes comments if an article is deleted ]); } } Use self::class is a best practice in modern PHP, as it prevents bugs if you ever decide to rename your classes, and your IDE can auto-complete and check it for you VideosTable.php You'll do the same thing for the Videos model, but change the model_name condition. // src/Model/Table/VideosTable.php namespace App\Model\Table; use Cake\ORM\Table; class VideosTable extends Table { public function initialize(array $config): void { // ... $this->hasMany('Comments', [ 'foreignKey' => 'foreign_id', 'conditions' => ['Comments.model_name' => self::class], // or 'Videos' 'dependent' => true, ]); } } CommentsTable.php This table is the owner of the polymorphic association. You can add associations here to easily access the related Article or Video from a Comment entity. // src/Model/Table/CommentsTable.php namespace App\Model\Table; use Cake\ORM\Table; class CommentsTable extends Table { public function initialize(array $config): void { // ... $this->belongsTo('Articles', [ 'foreignKey' => 'foreign_id', 'conditions' => ['Comments.model_name' => \App\Model\Table\ArticlesTable::class], // or 'Articles' ]); $this->belongsTo('Videos', [ 'foreignKey' => 'foreign_id', 'conditions' => ['Comments.model_name' => \App\Model\Table\VideosTable::class], // or 'Videos' ]); } }

Step 3: Using the Relationship

Now that everything is set up, you can fetch data as if it were a normal association. Fetching Comments for an Article: $article = $this->Articles->get(1, ['contain' => 'Comments']); // $article->comments will contain a list of comments for that article Creating a new Comment for a Video: $video = $this->Videos->get(2); $comment = $this->Comments->newEmptyEntity(); $comment->content = 'This is an awesome video!'; $comment->foreign_id = $video->id; $comment->model_name = \App\Model\Table\VideosTable::class; // or 'Videos' $this->Comments->save($comment); As you can see, the model_name and foreign_id fields are the secret sauce that makes this pattern work.

What About the Future? The Power of This Solution

Now that you've got comments working for both articles and videos, what if your app grows and you want to add comments to a new model, like Photos? With this polymorphic setup, the change is incredibly simple. You don't need to alter your comments table at all. All you have to do is: Create your photos table in the database. Add a new PhotosTable.php model. In the new PhotosTable's initialize() method, add the hasMany association, just like you did for Articles and Videos. // src/Model/Table/PhotosTable.php namespace App\Model\Table; use Cake\ORM\Table; class PhotosTable extends Table { public function initialize(array $config): void { // ... $this->hasMany('Comments', [ 'foreignKey' => 'foreign_id', 'conditions' => ['Comments.model_name' => self::class], 'dependent' => true, ]); } } That's it! You've just extended your application's functionality with minimal effort. This demonstrates the true power of polymorphic relationships: a single, scalable solution that can easily adapt to your application's evolving needs. It's a key pattern for building flexible and maintainable software.

Conclusion

This approach is flexible, scalable, and a great way to keep your database schema simple. Now that you know the basics, you can start applying this pattern to more complex problems in your own CakePHP applications!

Closing Advent Calendar 2024

This article is part of the CakeDC Advent Calendar 2024 (December 24th 2024) That’s a wrap on the CakeDC 2024 advent calendar blog series. Did you get to read all of them? Hopefully you obtained some useful information to use in your future baking. We would love to get your feedback, feel free to share! It is still hard to believe that 2024 is almost over, but we are looking forward to an extraordinary 2025. On behalf of CakeDC, we want to thank our team for all the hours of hard work they put in this year. Also, thank you to our clients for trusting us with your CakePHP projects, it is an absolute pleasure getting to work with each of you. We are thankful for the great relationships we have built, or carried on in the last 12 months. For our CakePHP community, especially the core team, please know how incredibly grateful we are for your support of the framework. There is a reason that Cake is still around after 20 years, and it’s great developers like you, who dedicate their time and efforts to keep the code going. THANK YOU, THANK YOU, THANK YOU. As far as what is to come for CakePHP in 2025, stay tuned. However, I am told that there are some top secret (not really, we are opensource after all) talks about CakePHP 6 happening. With the release of PHP 8.4, I am sure some awesome features will be implemented in Cake specifically. We will also be celebrating 20 years of CakePHP next year, can you believe it? CakeFest will be in honor of all core members past and present, and it may be a good time to introduce some new ones as well. If you are a core member (or former), we would love to have you attend the conference this year. The location will be announced soon. Interested in getting involved or joining the core team? You can find some helpful links here: https://cakephp.org/get-involved We hope you enjoyed our gift this year, it’s the least we could do. Wishing you a happy holiday season from our CakeDC family to yours. See you next year! … sorry, I had to do it. :) Also, here are some final words from our President: Larry Masters.

A Christmas Message to the CakePHP Community

As we gather with loved ones to celebrate the joy and hope of the Christmas season, I want to take a moment to reflect on the incredible journey we’ve shared this year as part of the CakePHP community. This is a special time of year when people around the world come together to celebrate love, grace, and the hope that light brings into the world. It’s also a time to give thanks for the connections that make our lives richer. The CakePHP framework has always been about more than just code, it’s about people. It’s the collective effort of contributors from around the world who believe in building something better, together. To everyone who has shared their expertise, contributed code, written documentation, tested features, or offered guidance to others, I want to express my deepest gratitude for your dedication and passion. As we approach 2025, it brings even greater meaning to reflect on how far we’ve come. Next year marks the 20th anniversary of CakePHP. From the first lines of code to the projects we support today, the journey has been nothing short of remarkable. As we look ahead to the new year, let us carry forward this spirit of generosity, collaboration, and unity. Together, we can continue to empower developers, build exceptional tools, and foster a community that is inclusive, welcoming, and supportive. On behalf of everyone at Cake Development Corporation, I wish you and your families a blessed Christmas filled with peace, joy, and love. May the new year bring us more opportunities to create, connect, and grow together. Thank you for being part of this journey. Merry Christmas and a very Happy New Year to everyone. With gratitude, Larry Masters This article is part of the CakeDC Advent Calendar 2024 (December 24th 2024)

We Bake with CakePHP