CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Building Dynamic Web Applications with CakePHP and HTMX: A Practical Guide

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

Other Articles in the Series

This article explores how to integrate htmx with CakePHP to create more dynamic and interactive web applications while writing less JavaScript code. We'll cover the basics of htmx, its setup with CakePHP, and practical examples to demonstrate its power.

Introduction to htmx library

htmx is a modern JavaScript library that allows you to access AJAX, CSS Transitions, WebSockets, and Server Sent Events directly in HTML, using attributes. It's designed to be simple, powerful, and a natural extension of HTML's existing capabilities.

The library's main purpose is to allow you to build modern user interfaces with the simplicity of HTML, reducing the need for complex JavaScript. Instead of writing JavaScript to handle frontend interactions, you can use HTML attributes to define dynamic behaviors.

htmx works by intercepting HTML events (like clicks or form submissions), making HTTP requests in the background, and updating the DOM with the response. This approach, often called "hypermedia-driven applications," allows for rich interactivity while maintaining the simplicity of the web's original architecture.

Basic setup with CakePHP

To get started with htmx in your CakePHP application, follow these steps:

  1. Install the CakePHP htmx plugin using Composer:

    composer require zunnu/cake-htmx
  2. Load the htmx JavaScript library in your layout file (templates/layout/default.php):

    <?= $this->Html->script('https://unpkg.com/[email protected]') ?>
  3. Load the plugin in your application (Application.php):

    public function bootstrap(): void
    {
    // ... other plugins
    $this->addPlugin('CakeHtmx');
    }

Boost your CakePHP application with htmx

One of the simplest yet powerful features of htmx is the hx-boost attribute. By adding this attribute to any container element (often the <body> tag), you can automatically enhance all anchor tags and forms within that container to use AJAX instead of full page loads.

Basic Implementation

Add the hx-boost attribute to your layout file (templates/layout/default.php):

<body hx-boost="true">
    <?= $this->Flash->render() ?>
    <?= $this->fetch('content') ?>
</body>

With this single attribute, all links and forms in your application will automatically use AJAX requests instead of full page loads. The content will be smoothly updated without refreshing the page, while maintaining browser history and back/forward button functionality.

How it Works

When hx-boost is enabled:

  1. Clicks on links (<a> tags) are intercepted
  2. Form submissions are captured
  3. Instead of a full page load, htmx makes an AJAX request
  4. The response's <body> content replaces the current page's <body>
  5. The URL is updated using the History API
  6. Browser history and navigation work as expected

Practical Example

Here's a typical CakePHP navigation setup enhanced with hx-boost:

<!-- templates/layout/default.php -->
<!DOCTYPE html>
<html>
<head>
    <title><?= $this->fetch('title') ?></title>
    <?= $this->Html->script('https://unpkg.com/[email protected]') ?>
</head>
<body hx-boost="true">
    <nav>
        <?= $this->Html->link('Home', ['controller' => 'Pages', 'action' => 'display', 'home']) ?>
        <?= $this->Html->link('Posts', ['controller' => 'Posts', 'action' => 'index']) ?>
        <?= $this->Html->link('About', ['controller' => 'Pages', 'action' => 'display', 'about']) ?>
    </nav>

    <main>
        <?= $this->Flash->render() ?>
        <?= $this->fetch('content') ?>
    </main>
</body>
</html>

Selective Boosting

You can also apply hx-boost to specific sections of your page:

<!-- Only boost the post list -->
<div class="post-section" hx-boost="true">
    <?php foreach ($posts as $post): ?>
        <?= $this->Html->link(
            $post->title,
            ['action' => 'view', $post->id],
            ['class' => 'post-link']
        ) ?>
    <?php endforeach; ?>
</div>

<!-- Regular links outside won't be boosted -->
<div class="external-links">
    <a href="https://example.com">External Link</a>
</div>

Excluding Elements

You can exclude specific elements from being boosted using hx-boost="false":

<body hx-boost="true">
    <!-- This link will use AJAX -->
    <?= $this->Html->link('Profile', ['controller' => 'Users', 'action' => 'profile']) ?>

    <!-- This link will perform a full page load -->
    <a href="/logout" hx-boost="false">Logout</a>
</body>

The hx-boost attribute provides a simple way to enhance your CakePHP application's performance and user experience with minimal code changes. It's particularly useful for:

  • Navigation between pages
  • Form submissions
  • Search results
  • Pagination
  • Any interaction that traditionally requires a full page reload

By using hx-boost, you get the benefits of single-page application-like behavior while maintaining the simplicity and reliability of traditional server-rendered applications.

Going deeper with htmx with custom attributes

First, let's see how we can transform a traditional CakePHP index page to use htmx.

Index page example

Here's a traditional index page without htmx, showing a list of posts:

// PostsController.php
public function index()
{
    $query = $this->Posts->find();
    $posts = $this->paginate($query, ['limit' => 12]);
    $this->set(compact('posts'));
}
<!-- templates/Posts/index.php -->
<div class="posts index content">
    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th><?= $this->Paginator->sort('id') ?></th>
                    <?php // .... ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($posts as $post): ?>
                    <?php // .... ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="paginator">
        <ul class="pagination">
            <?php // .... ?>
        </ul>
    </div>
</div>

Index page example with htmx

Now, let's enhance the same page with htmx to handle pagination and sorting without page reloads:

// PostsController.php
public function index()
{
    $query = $this->Posts->find();
    $posts = $this->paginate($query, ['limit' => 12]);
    $this->set(compact('posts'));
    if($this->getRequest()->is('htmx')) {
        $this->viewBuilder()->disableAutoLayout();
        $this->Htmx->setBlock('posts');
    }
}
<!-- templates/Posts/index.php -->
<div id="posts" class="posts index content">
<?php $this->start('posts'); ?>
    <div class="table-container">
        <div id="table-loading" class="htmx-indicator">
            <div class="spinner"></div>
        </div>
        <div class="table-responsive">
            <table>
                <thead
                    hx-boost="true"
                    hx-target="#posts"
                    hx-indicator="#table-loading"
                    hx-push-url="true"
                >
                    <tr>
                        <th><?= $this->Paginator->sort('id') ?></th>
                        <?php // .... ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($posts as $post): ?>
                        <?php // .... ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="paginator"
            hx-boost="true"
            hx-target="#posts"
            hx-indicator="#table-loading"
            hx-push-url="true"
        >
            <ul class="pagination">
                <?php // .... ?>
            </ul>
        </div>
    </div>
<?php $this->end(); ?>
</div>
<?= $this->fetch('posts'); ?>

Now let's look at the changes we made to the controller and the HTML structure.

Controller Changes

In the controller, we've added htmx-specific handling. When a request comes from htmx, we:

  1. Disable the layout since we only want to return the table content
  2. Use the Htmx helper to set a specific block that will be updated
  3. Maintain the same pagination logic, making it work seamlessly with both regular and htmx requests

Out-of-Band (OOB) Swaps with htmx

htmx supports Out-of-Band (OOB) Swaps, which allow you to update multiple elements on a page in a single request. This is particularly useful when you need to update content in different parts of your page simultaneously, such as updating a list of items while also refreshing a counter or status message.

How OOB Works

  1. In your response HTML, include elements with hx-swap-oob="true" attribute
  2. These elements will update their counterparts on the page based on matching IDs
  3. The main response content updates normally, while OOB content updates independently

HTML Structure Changes

The main changes to the HTML structure include:

  1. Adding an outer container with a specific ID (posts) for targeting updates
  2. Wrapping the content in a block using $this->start('posts') and $this->end() to allow for OOB swaps
  3. Adding a loading indicator element
  4. Implementing htmx attributes on the table header and paginator sections

HTMX Attributes Explained

The following htmx attributes were added to enable dynamic behavior:

  • hx-boost="true": Converts regular links into AJAX requests
  • hx-target="#posts": Specifies where to update content (the posts container)
  • hx-indicator="#table-loading": Shows/hides the loading spinner
  • hx-push-url="true": Updates the browser URL for proper history support

These attributes work together to create a smooth, dynamic experience while maintaining proper browser history and navigation.

Loading Indicator Implementation

The loading indicator provides visual feedback during AJAX requests:

  1. A centered spinner appears over the table during loading
  2. The table content is dimmed using CSS opacity
  3. The indicator is hidden by default and only shows during htmx requests
  4. CSS transitions provide smooth visual feedback
.table-container {
    position: relative;
    min-height: 200px;
}

.htmx-indicator {
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
}

.htmx-indicator.htmx-request {
    display: block;
}

.htmx-indicator.htmx-request ~ .table-responsive,
.htmx-indicator.htmx-request ~ .paginator {
    opacity: 0.3;
    pointer-events: none;
    transition: opacity 0.2s ease;
}

.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

Problems with current htmx implementation and boost implementation

Browser History and Back Button Issues

When using htmx with hx-boost or AJAX requests, you might encounter issues with the browser's back button showing partial content. This happens because:

  1. htmx requests only return partial HTML content
  2. The browser's history stack stores this partial content
  3. When users click the back button, the partial content is displayed instead of the full page

Preventing Cache Issues in Controllers

To disable htmx caching by browsers, you can add the following headers to your response in your controller:

    if ($this->request->is('htmx') || $this->request->is('boosted')) {
        $this->response = $this->response
            ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
            ->withHeader('Pragma', 'no-cache')
            ->withHeader('Expires', '0');

    }

General Solution

Prevent caching issues with htmx requests by creating a middleware:

// src/Middleware/HtmxMiddleware.php
public function process(ServerRequest $request, RequestHandler $handler): Response
{
    $response = $handler->handle($request);

    if ($request->is('htmx')) {
        return $response
            ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
            ->withHeader('Pragma', 'no-cache')
            ->withHeader('Expires', '0');
    }

    return $response;
}

Conclusion

htmx is a powerful library that can significantly enhance the interactivity and user experience of your CakePHP applications. By using htmx attributes, you can create dynamic, responsive, and efficient web applications with minimal JavaScript code.

Demo Project for Article

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

This article is part of the CakeDC Advent Calendar 2024 (December 2th 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