CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Dynamic Enums (CakePHP 5 / PHP 8.3)

This article is part of the CakeDC Advent Calendar 2024 (December 3rd 2024)

In modern PHP development, utilizing constants and enums can significantly improve code readability, maintainability, and robustness. This article explores practical implementations of constants and enums in a CakePHP application.  By leveraging these features, developers can write cleaner and more efficient code. Let's dive into the specifics with code examples and practical use cases.
 

1.- Define a constant class of user roles:

src/Constants/UserRoles.php namespace App\Constants; class UserRoles { public const string ADMIN = 'admin'; public const string EDITOR = 'editor'; public const string VIEWER = 'viewer'; }

2.- Define an Enum class for the status of the posts:

src/Enum/PostStatus.php namespace App\Enum; enum PostStatus: string { case DRAFT = 'draft'; case PUBLISHED = 'published'; case ARCHIVED = 'archived'; public static function list(): array { return [ self::DRAFT->value => __('DRAFT'), self::PUBLISHED->value => __('PUBLISHED'), self::ARCHIVED->value => __('ARCHIVED'), ]; } }

3.- Define an Enum class for the status of the comments:

src/Enum/CommentStatus.php namespace App\Enum; enum CommentStatus: string { case APPROVED = 'approved'; case DECLINED = 'declined'; public static function list(): array { return [ self::APPROVED->value => __('APPROVED'), self::DECLINED->value => __('DECLINED'), ]; } }

4.- Check the dynamic use in the access to the Enums values.

templates/Pages/enums.php // Dynamic constants new in php 8.3 and php 8.4 use App\Constants\UserRoles; use App\Enum\PostStatus; $roleName = 'ADMIN'; $roleValue = UserRoles::{$roleName}; // Dynamically accesses UserRoles::ADMIN echo "Role Value: " . $roleValue; // Print “Role Value: admin” // Dynamic Enum members new in php 8.3 and php 8.4 $statusName = 'PUBLISHED'; $statusValue = PostStatus::{$statusName}->value; // Dynamically accesses PostStatus::Published echo "Post Status: " . $statusValue; // Print “Post Status: published”

5.- We can also use its functions, for example “list” for selectors, and print its value.

//generate a select element with all status options echo $this->Form->control('status', ['options' => PostStatus::list(), 'empty' => true]); //print the text associated with the status value echo h(PostStatus::list()['published']);

6.- They can be used dynamically in query operations, for example: to get a post and only your comments approved.

src/Controller/PostsController.php $postWithCommentsApproved = $this->Posts ->find('onlyCommentsByStatusEnum', status: CommentStatus::APPROVED) ->contain(['Users']) ->where(['Posts.id' => $id]) ->firstOrFail(); src/Model/Table/PostsTable.php public function findOnlyCommentsByStatusEnum(SelectQuery $query, CommentStatus $status): SelectQuery { return $this->find() ->contain(['Comments' => function ($q) use ($status) { return $q->where([ 'Comments.status' => $status->value, ]); }]); } You can see a complete example in https://github.com/ACampanario/advent2024.

Building Dynamic Web Applications with...

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)

Our Gift To You - The CakeDC Advent Ca...

So, we are back! It’s been a while, right?    We are aware that the blog has been quiet, but boy do we have a surprise for you all.    First, let’s recap this year… a lot of releases from CakeDC like plugins and contributions to the latest CakePHP versions. We, like every other baker, have been enjoying all of the new features that Cake 5 has presented. We look forward to seeing what the core team has in store next. It is a company goal to be more involved in the CakePHP community in 2025, so you’ll be seeing some familiar faces in the community channels.     Oh, and I would be remiss if I did not also express our gratitude to our clients. We have had a great year with all of you.  We are so thankful to work with each and every one of you and it has been a pleasure baking code for your many projects.    Now… on to the good stuff.  The team has decided to write a series of blogs, in the form of an advent calendar. It is the holiday season after all. So what can you expect? I don’t want to give away too much, but I will say you’ll get to savor some tasty cake related topics like: HTMX, JWT with CakePHP, plugins, security, PHP 8.4 … and so much more.    This is the gift that keeps on giving... the whole month. So pre heat those ovens… and get ready for a new blog each day from the CakeDC team! 
CakeDC Advent Calendar 2024! 

Build a Single Page Application Using ...

The Inertia Plugin allows a CakePHP application to integrate Vue 3 components in the front end, without the need to write a specific API for data transfer. This is done  by adding a Middleware and view classes that facilitate the conversion of objects and data in JSON almost automatically, as well as the direct load in the components. The plugin is thought of as a base to extend and use your app’s specific controllers and views from. Just because  it works out of the box doesn't mean it is intended to be used exactly as is,  but this will  provide you a good kick start. See the repo here: https://github.com/CakeDC/cakephp-inertia

Requirements

  • CakePHP 4.5
  • PHP >= 8.1
  • NodeJS 18.9 (only for build Vue Components, not required on running site)

 

Step 1: Create a basic CakePHP install

  For this example I will use a basic installation using Docker and Composer.  First you must create project from cakephp/app  
$> composer create-project --prefer-dist cakephp/app:~4.5 inertia_app $> cd inertia_app $> cp config/app_local.example.php config/app_local.php
  Then write an docker-compose.yml file as:
version: '3' services:   psql13:     image: postgres:13     container_name: inertia-app-postgres13     volumes:       - ./tmp/data/inertia-postgres13__db:/var/lib/postgresql:delegated     environment:       - POSTGRES_USER=my_app       - POSTGRES_PASSWORD=secret       - POSTGRES_DB=my_app       - PGUSER=my_app       - PGDATABASE=my_app       - PGPASSWORD=secret     ports:       - '7432:5432'     cakephp:     image: webdevops/php-nginx:8.1     container_name: inertia-app-cakephp     working_dir: /application     volumes:       - ./:/application:cached       - ~/.ssh:/home/application/.ssh:ro     environment:       - WEB_DOCUMENT_ROOT=/application/webroot       - DATABASE_URL=postgres://my_app:secret@inertia-app-postgres13:5432/my_app     ports:       - "9099:80"
  Launch the container and go to http://localhost:9099/  
$> docker-compose up -d
 

Step 2: Add CakePHP Inertia plugin

  Install plugin via command line:
$> composer require cakedc/cakephp-inertia
  Once installed enable it in src/Application.php, adding at the bottom of bootstrap function:
$this->addPlugin('CakeDC/Inertia');
  or by command line:
$> bin/cake plugin load CakeDC/Inertia

 

Step 3: Create Vue App and install it

  To create Vue App type in command line:
$> bin/cake create_vue_app
  This command create in the resources directory the files that use our App, also create in root directory the files:
  • webpack.mix.js
  • package.json
  Then in root directory install with NPM:
$> npm install

 

Step 4: Create simple SPA (Single Page Application)

  Create a single page called dashboard that show values sets in a controller action We need to first add InertiaResponseTrait  
use CakeDC\Inertia\Traits\InertiaResponseTrait;   class PagesController extends AppController {    use InertiaResponseTrait;    ...  ...   }
  Create a new function that would look like this:
public function dashboard() {   //set default php layout of plugin that use vue   $this->viewBuilder()->setTheme('CakeDC/Inertia');     $page = [       'text' => 'hello world 1',       'other' => 'hello world 2',   ];   $this->set(compact('page')); }
  in config/routes.php uncomment lines to catch all routes:
$builder->connect('/{controller}', ['action' => 'index']); $builder->connect('/{controller}/{action}/*', []);
and comment line:
$builder->connect('/pages/*', 'Pages::display');
  Then create file resources/js/Components/Pages/Dashboard.vue that would look like this:
<script setup> import Layout from '../Layout' import { Head } from '@inertiajs/vue3' import {onMounted} from "vue";   defineProps({     csrfToken: String,     flash: Array,     page: Array, })     onMounted(() => {     console.log('Component Dashboard onMounted hook called') }) </script>   <template>     <Layout>         <Head title="Welcome" />         <h1>Welcome</h1>         <p>{{page.text}}</p>         <p>{{page.other}}</p>     </Layout> </template>
  On root directory execute:
$> npm run dev
  IMPORTANT: Whenever you modify the .vue templates, you must run this script. Go to http://localhost:9099/pages/dashboard to see that Dashboard Vue Component prints values assignments on Dashboard CakePHP function.
   

 

Step 5: Bake CRUD system

  For this example, we use sql file on config/sql/example/postgresql.pgsql   That creates a database with the relations     Once the database has been created, bake models and controllers as normal using:
$> bin/cake bake model Pages --theme CakeDC/Inertia $> bin/cake bake controller Pages --theme CakeDC/Inertia $> bin/cake bake model Tags --theme CakeDC/Inertia $> bin/cake bake controller Tags --theme CakeDC/Inertia $> bin/cake bake model Categories --theme CakeDC/Inertia $> bin/cake bake controller Categories --theme CakeDC/Inertia
  and bake templates using vue_template instead of template as:
$> bin/cake bake vue_template Pages --theme CakeDC/Inertia $> bin/cake bake vue_template Tags --theme CakeDC/Inertia $> bin/cake bake vue_template Categories --theme CakeDC/Inertia
  Again run:
$> npm run dev
  You can the results from this example by going to http://localhost:9099/pages/index   In the following recording you can see how to add, edit and delete a record without reloading the page at any time.

 

Step 6: Using prefix and adding a navigation menu

  Add route to prefix Admin on config/routes.php
$builder->prefix('admin', function (RouteBuilder $builder) {    $builder->fallbacks(DashedRoute::class); });
  To generate controllers and template with a prefix use --prefix option of bake command as:
$> bin/cake bake controller Pages --prefix Admin --theme CakeDC/Inertia $> bin/cake bake controller Tags --prefix Admin --theme CakeDC/Inertia $> bin/cake bake controller Categories --prefix Admin --theme CakeDC/Inertia $> bin/cake bake vue_template Pages --prefix Admin --theme CakeDC/Inertia $> bin/cake bake vue_template Tags --prefix Admin --theme CakeDC/Inertia $> bin/cake bake vue_template Categories --prefix Admin --theme CakeDC/Inertia
  You can add a horizontal menu to navigate through controllers   Edit resources/Components/Layout.vue and put inside header tag links as:
<header>    <Link as="button" href="/pages/index" class="button shadow radius right small">Pages</Link>    <Link as="button" href="/tags/index" class="button shadow radius right small">Tags</Link>    <Link as="button" href="/categories/index" class="button shadow radius right small">Categories</Link> </header>
  Again run:
$> npm run dev
  You can see the results from this  example by going to http://localhost:9099/admin/pages/index   In the following recording you can see how to add, edit and delete a record without reloading the page at any time and navigate through pages, tags and categories.

  Hopefully this example will make your experience easier! Let us know: [email protected].

When and why should you upgrade to Cak...

CakePHP 5.0.0 was released on September 10th. The current version as of today is 5.0.3 (released Nov 28th and compatible with PHP 8.3 https://github.com/cakephp/cakephp/releases/tag/5.0.3). You might be asking yourself some questions related to the upgrade… here's what we've been recommending to our clients to do since version 5 was released. Leaving aside the obvious reasons for an upgrade, today we're going to categorize the decision from 2 different points of view: Your current CakePHP version, and your role in the project.

When should you upgrade? 

  We are going to use current CakePHP version as the main criteria: * If you are in CakePHP <= 2   * We strongly recommend an upgrade as soon as possible. If you are unable to upgrade, try to keep your PHP version and all the underlying dependencies as fresh as you can and isolate the application as much as possible. If your application is internal, consider using a VPN blocking all outside traffic. If your site is open to the public, consider using an isolated environment, hardened. Adding a web application firewall and a strict set of rules could also help to mitigate potential security issues. Even if CakePHP is very secure, the older versions of CakePHP, like  1 and 2  have a very old code base , and other vendors/ libraries could be a serious security risk for your project at this point.   * If you are in CakePHP 3.x   * The effort to upgrade at least to CakePHP 4.x should not be a blocker. We would recommend upgrading at least to the latest CakePHP 4.5.x. You can actually "ignore" the deprecations for now, you don't need to plan for upgrading your authentication/authorization layers just yet, focus on getting your project stable and up to CakePHP 4.5.x in the first round.   * If you are in CakePHP 4.x   * Upgrading to CakePHP 5.x is not an immediate priority for you.   * I would say, 2024 is a good time to start planning for an upgrade. Feature and bugfix releases for 4.x will continue until September 2025. Security fixes will continue for 4.x until September 2026. You have plenty of time to consider an upgrade, and take advantage of newer (and faster!) PHP versions.  

Why should you upgrade? 

  We are going to use your role in the project to provide some good reasons: * If you are a developer   * More strict types, meaning better IDE support and more errors catched at development time.   * New features in CakePHP 5.x will make your code more readable, like Typed finder parameters https://book.cakephp.org/5/en/appendices/5-0-migration-guide.html#typed-finder-parameters      * Quality of life features, reducing development time like https://book.cakephp.org/5/en/appendices/5-0-migration-guide.html#plugin-installer   * Compatibility with PHP 8.3 for extra performance & support   * If you are a manager   * Ensure your development team is forced to drop old auth code and embrace the new authentication/authorization layer https://book.cakephp.org/5/en/appendices/5-0-migration-guide.html#auth   * The new authentication layer will allow you to easily integrate features like single sign on, two factor authentication or hardware keys (like Yubikeys), as there are plugins available handling all these features.   * Get an extended support window. CakePHP is one of the longest maintained frameworks out there, upgrading to CakePHP 5 will keep your core maintained past 2026.   * Upgrade to PHP 8.3 and force legacy vendors to be up to date with the new version, this will also push your team to get familiar with the new PHP core features.   * If you are an investor, not directly related with the project day-to-day operations   * Secure your inversion for a longer period.   * Reduce your exposure to security issues.   * Send a strong message to your partners, keeping your product updated with the latest technology trends.   * Send a strong message to your team, investing in the upgrade of your application will let them know the project is aiming for a long term future.   In conclusion, upgrading to CakePHP 5 is a good move for 2024 whether you're a developer, manager, or investor. The version 5 is stable and ready to go. Staying current becomes not just a best practice but a strategic advantage.   If you are in doubt, feel free to contact us. We'll review your case (for free) and provide an actionable recommendation based on your current situation in the next business day.  

A quick CakePHP Local environment with...

In the realm of web development, a seamless local environment is the bedrock for efficient and stress-free coding. Enter DDEV, a powerful tool that simplifies the setup process and empowers developers to dive into their projects with ease. In this blog post, we'll embark on a journey to demystify the process of setting up a local development environment using DDEV. Whether you're a seasoned developer or just starting in the world of web development, optimizing your local environment can significantly enhance your workflow.

Pre Conditions :

Install Docker https://docs.docker.com/get-docker/ and install DDEV https://ddev.readthedocs.io/en/stable/

Step 1: Create a new CakePHP project skeleton 

composer create-project cakephp/app myproject A new folder "myproject" will be created with a CakePHP project skeleton inside. Go to this new directory and proceed with the following instructions.

Step 2: Initial ddev setup

Run ddev config
This will do the initial ddev setup, press enter for all questions.  Run ddev auth ssh
This will add ssh key authentication to the ddev-ssh-auth container

Step 3: Adjust the settings

Inside "myproject" a new .ddev folder will be created, open config.yaml  and adjust there: php version, database and the database url environment.  For PHP:
php_version: "8.1"

For the database: database: type: mysql version: "8.0" For the environment variable: web_environment: - DATABASE_URL=mysql://db:db@db/db

Step 4: Start ddev

ddev start  This will spin up the project.

Step 5: Open your application

ddev launch This will open your project in a browser.   Once you have the application up and running, some useful commands you could run are:
  • ddev composer to execure composer
  • ddev mysql to get into the database
  • ddev ssh takes you into the web container.
In this link https://ddev.readthedocs.io/en/latest/users/usage/cli/ you can see more useful commands.   Hope you enjoy playing with DDEV!

 

   

 

 

CakeFest 2023 Recap

CakeFest 2023 once again brought together developers from around the world for a weekend of baking (code), insightful talks, and community building. This year's event, featuring speakers from eight different countries and attendees joining both in person and via live streaming, was a refreshing convergence of passion and technology.

International Flavor:

One of the highlights of CakeFest 2023 was its international reach. Speakers from the United States, Canada, the Netherlands, Austria, Germany, Brazil, and Spain graced the virtual and physical stages, sharing experiences in the world of CakePHP and software development. This lineup added a diverse perspective to the event's discussions.  

A Weekend of Learning and Networking:

CakeFest attendees enjoyed a weekend filled with learning opportunities, covering things from beginner workshops to cutting-edge software development trends, to the future of CakePHP. Workshops, panels, and presentations provided valuable insights and knowledge of the framework. We hope that everyone had the chance to expand their skills, connect with other developers, and forge new professional relationships. When CakeFest wasn't in session, the core/CakePHP team and attendees spent a lot of time getting to know each other… Groups went to lunch and dinner every day of the event. This is probably my favorite part of the physical conferences.    

Baking and Code:

Day 1 consisted of 2 full workshops from Jorge González and lead core developer Mark Story. The third workshop presented by Kevin Pfeifer was included in day 2’s hybrid model. Followed by talks from: John Killcommons (keynote) of Zulucare/Zulucloud, Rafael Queiroz (Github actions for beginners and applied to CakePHP basic projects), Celso Fontes (PGE Digital, a successful CakePHP project in Rio de Janeiro's Attorney), and Andres Campanario (Integration of inertiajs on CakePHP to bake CRUD SPA).    Day 3’s speakers included: Remy Bertot (keynote) of Passbolt, Mark Scherer  (How to use your IDE effectively for CakePHP), Alejandro Ibarra (Unveiling the Ultimate Showdown: A Comparative Analysis of Local Development Tools), Stefan Koopmanschap (Domain-Driven Design: The Basics), Umer Salman (Agile Deployment of CakePHP Web Applications in a Hybrid Kubernetes Cluster), and Wim Godden (Websockets as the glue to interactivity).    It was a weekend worth remembering for sure. The unique blend of networking and code at CakeFest allowed attendees to see just how far CakePHP has come, and will go, plus some pretty cool things built with the framework.     

The Cake Ceremony:

No CakeFest would be complete without the much-anticipated cake ceremony. We hope that those attending virtually were able to enjoy some with us. In LA, we carried on the tradition of allowing Mark Story to be the “cutter of the cake”. Now that I think about it, he never asks to cut the cake, but it’s a honor nonetheless. 

   

Conclusion:

CakeFest 2023 was a celebration of passion, knowledge, and creativity. With its global reach, experienced speaker lineup, and faithful community, we believe that the event left attendees inspired and eager to continue their works using Cake. We also learned about all of the cool places that CakePHP is being utilized, from the attorney general's office in Brazil, all the way to nasa using some CakePHP in space (more or less). We also heard from some of our CakePHP core developers - specifically their thoughts on CakePHP 5 and what’s to come. You can see a lot of photos on Facebook and Twitter and the edited presentation videos will be posted to YouTube soon. We are working on getting slides uploaded into the CakeFest site as we speak (or type).    Someone said to me that there's a little bit of magic in every slice of cake and every line of code… I think that pretty well sums up our great weekend at CakeFest.

How to push Docker image to Container ...

The title speaks for itself, let’s jump right in! As a preliminary step, we start from a user registered in DigitalOcean with a validated account. Use the doctl tool for the entire communication process with DigitalOcean.

Step 1: Install doctl

$ cd ~
$ wget https://github.com/digitalocean/doctl/releases/download/v1.71.0/doctl-1.71.0-linux-amd64.tar.gz
$ tar xvf doctl-1.71.0-linux-amd64.tar.gz
$ sudo mv doctl /usr/local/bin
 

Step 2: Create an API token

  Go to https://cloud.digitalocean.com/account/api/tokens Generate new token for read and write and save apart the value of token generated <TOKEN NAME>: personaltoken 
<TOKEN VALUE>: 6e981fc2a674dbb7a610b9b85d0c8b00

Step 3: Use the API token to grant account access to doctl

$ doctl auth init --context personaltoken
Validating token... OK
Prompt for <TOKEN VALUE>, then enter it and press return 
 

Step 4: Validate that doctl is working

$ doctl auth init  Validating token... OK
  Prompt for <TOKEN VALUE>, then enter it and press return  Validate by obtaining the account information
$ doctl account get Email      Droplet Limit    Email Verified    UUID         Status [email protected]    10     true     5415bbf8-d501-4096-9b75-ab781c017948    active
 

Step 5: Create a Container Registry with doctl

<MY-REGISTRY-NAME> : container-nyc-795 <REGION> : nyc3
$ doctl registry create container-nyc-795 --region nyc3 Name       Endpoint        Region slug container-nyc-795    registry.digitalocean.com/container-nyc-795    nyc3

Important: the region of the Container registry and Kubernetes cluster MUST be the same Keep in mind that container names must be unique, must be lowercase, and only accepts alphanumeric characters and hyphens.  

Step 6: Login to authenticate docker with your registry

$ doctl registry login
Logging Docker in to registry.digitalocean.com
 

Step 7: Create kubernetes cluster

$ doctl kubernetes cluster create cluster-static-example --region nyc3 Notice: Cluster is provisioning, waiting for cluster to be running ................................................................... Notice: Cluster created, fetching credentials Notice: Adding cluster credentials to kubeconfig file found in "/home/andres/.kube/config" Notice: Setting current-context to do-nyc3-cluster-static-example ID                                      Name                      Region    Version        Auto Upgrade    Status     Node Pools d24f180b-6007-4dbc-a2fe-3952801570aa    cluster-static-example    nyc3      1.22.7-do.0    false           running    cluster-static-example-default-pool
Important: the region of the Container registry and Kubernetes cluster MUST be the same here as well.  This operation isn’t a fast process.  

Step 8: Integrate kubernetes cluster in Container register

$ doctl kubernetes cluster registry add cluster-static-example
 

Step 9: Get token certificate and connect to cluster

$ doctl kubernetes cluster kubeconfig save cluster-static-example Notice: Adding cluster credentials to kubeconfig file found in "/home/andres/.kube/config" Notice: Setting current-context to do-nyc3-cluster-static-example
To validate this, use the kubectl tool to get context. If is not installed, get the last version you find - for example in googleapis
$ wget https://storage.googleapis.com/kubernetes-release/release/v1.23.5/bin/linux/amd64/kubectl
$ chmod +x kubectl
$ sudo mv kubectl /usr/local/bin/
Check with
$ kubectl config current-context
do-nyc3-cluster-static-example
Here, you see: bash prompt do-ny3-cluster-sttic-example. That is the context you created in Step 7
 

Step 10: Generate docker image, tag and push to DigitalOcean

We assume that the user already has docker installed
$ mkdir myapp
$ mkdir myapp/html
$ nano myapp/Dockerfile
  Inside Dockerfile put   
FROM nginx:latest
COPY ./html/hello.html /usr/share/nginx/html/hello.htm
l
  We create simple Dockerfile with NGINX Server and copy the file hello.html in the default html of nginx  
$ nano myapp/html/hello.html
  Inside hello.html put  
<!DOCTYPE html> <html>  <head>    <title>Hello World!</title>  </head>  <body>    <p>This is an example of a simple HTML page served from the Nginx container.</p>  </body> </html>
Then build a docker image file tag with repository and push with docker
 
$ cd myapp
$ docker build -t registry.digitalocean.com/container-nyc-795/static-app .
Sending build context to Docker daemon  3.584kB Step 1/2 : FROM nginx:latest latest: Pulling from library/nginx c229119241af: Pull complete 2215908dc0a2: Pull complete 08c3cb2073f1: Pull complete 18f38162c0ce: Pull complete 10e2168f148a: Pull complete c4ffe9532b5f: Pull complete Digest: sha256:2275af0f20d71b293916f1958f8497f987b8d8fd8113df54635f2a5915002bf1 Status: Downloaded newer image for nginx:latest  ---> 12766a6745ee Step 2/2 : COPY ./html/hello.html /usr/share/nginx/html/hello.html  ---> 2b9be913c377 Successfully built 2b9be913c377 Successfully tagged registry.digitalocean.com/container-nyc-795/static-app:latest   $ docker images REPOSITORY                                               TAG       IMAGE ID       CREATED         SIZE registry.digitalocean.com/container-nyc-795/static-app   latest    2b9be913c377   2 minutes ago   142MB   $ docker push registry.digitalocean.com/container-nyc-795/static-app Using default tag: latest The push refers to repository [registry.digitalocean.com/container-nyc-795/static-app] ac03ae036a53: Pushed ea4bc0cd4a93: Pushed fac199a5a1a5: Pushed 5c77d760e1f4: Pushed 33cf1b723f65: Pushed ea207a4854e7: Pushed 608f3a074261: Pushed latest: digest: sha256:22615ad4c324ca5dc13fe2c3e1d2d801bd166165e3809f96ed6a96a2b2ca2748 size: 1777


Step 11: Create app

Create file example-static-app.yaml and insert: alerts:                                 
- rule: DEPLOYMENT_FAILED               
- rule: DOMAIN_FAILED                   
name: example-static-app                
region: nyc                             
services:                               
- http_port: 80                         
  image:                                
    registry_type: DOCR                 
    repository: static-app              
    tag: latest                         
  instance_count: 2                     
  instance_size_slug: professional-xs   
  name: static-service                  
  routes:                               
  - path: /                             
  source_dir: /             
              Validate file with
$  doctl apps spec validate example-static-app.yaml
Create app
$ doctl apps create --spec example-static-app.yaml
Notice: App created
ID        Spec Name             Default Ingress    Active Deployment ID    In Progress Deployment ID    Created At     Updated At
55a7cb68-65b7-4ff1-b6af-388cdb1df507    example-static-app   2022-03-30 09:34:01.288257225 +0000 UTC    2022-03-30 09:34:01.288257225 +0000 UTC
If you access https://cloud.digitalocean.com/apps And in the live url + /hello.html you can see:

Step 12: Deploy app

If you modify the code of your app, you need to generate a new image with docker and push  (see step 10). Then you don’t need to create a new app, you need to deploy the image in the already created app, with the id executing the command to deploy in bash.
$  doctl apps create-deployment 55a7cb68-65b7-4ff1-b6af-388cdb1df507

 

How to generate deploy of Docker image to Container Registry on DigitalOcean Platform Apps

Once you have created the application (and if you have the code in gitlab), you can create a direct deployment of your code in the DigitalOcean container and deploy on top of your application.

Step 1: Define variables

First two variables are defined in gitlab. You can find these inside project in the left menu - enter in Settings > CI/CD > Variables $DIGITALOCEAN_API_KEY = token generated in DigitalOcean dashboard $APP_ID = previously generated application identifier   More can be defined as the name of the repository. The value of these variables will be injected into the file that we will create below in the Step 3  

 

Step 2: Register runner in gitlab

In your project in the left menu, go to Settings > CI/CD > Runners Create a specific runner for the project in the URL with registration token. Register GitLab Runner from the command line. It is important to use docker and privileged
# Download the binary for your system
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

# Give it permission to execute
sudo chmod +x /usr/local/bin/gitlab-runner

# Register runner
sudo gitlab-runner register -n --url https://git.cakedc.com --registration-token GR1348941gx7sgV3pZFQgRqg5qUR_ --executor docker --description "My Docker Runner" --docker-image "docker:19.03.12" --docker-privileged --docker-volumes "/certs/client"
 

Step 3: Create file gitlab-ci.yml 

The gitlab-ci.yml file takes care of

  • Authentication and identification using doctl in DigitalOcean
  • Generating and sending the docker image to the DigitalOcean container
  • Deploying the container image to an existing app
Create the file gitlab-ci.yml in the root of your project as
image: docker:20-dind

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: ""
  REPOSITORY_URL: registry.digitalocean.com/container-nyc-795/static-app
  CONTAINER_NAME: static-app

services:
  - name: docker:20-dind
    alias: docker
    command: ["--tls=false"]

before_script:
  - apk update
  - apk upgrade
  - apk add doctl --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community
  - docker info

build:
  stage: build
  script:
    - doctl auth init --access-token $DIGITALOCEAN_API_KEY
    - doctl account get     
    - echo $DIGITALOCEAN_API_KEY | docker login -u $DIGITALOCEAN_API_KEY --password-stdin registry.digitalocean.com
    - docker build -t $REPOSITORY_URL:latest .
    - docker push $REPOSITORY_URL
    - doctl apps create-deployment $APP_ID
Now, every time you do a git push in your project, the runner will automatically inject the variables defined previously in the gitlab-ci.yml file. Then, it will generate a docker image with docker (docker-in-docker) to create an image of your project, send it to the digitalocean repository and deploy it in the app configured.   That’s it!  

CakeFest 2021 Recap

Here we are again coming off of the CakeFest sugar high! I don’t even know where to begin.    Unfortunately, or fortunately - I haven’t decided, we had to do another virtual event. The safety of speakers, staff and attendees is very important to us, so a physical event was not the best option in our opinion with traveling.    However, after this event, I started thinking about the people who were able to attend from the comfort of their own homes or offices. These people may not have been able to travel or attend otherwise, and that gives me our silver lining. Not to mention that we had more ticket sales this year than any of our previous events (at least that I can remember).    The theme, for me anyway, ha ha, was traveling the world, ironically. We started in the Canary Islands, traveled to Germany, to Canada, to England and Austria. We had new faces from the US, the Czech Republic and even Japan - and more! This is, as I’ve mentioned, one of the best things about the CakePHP community, we have community members all over the world. This was our chance to come together.    So let’s get to the event. Here’s what you may have missed: 

Workshops:

Workshop 1 Jorge González (Twitter: @steinkelz) Topics covered included: 0:00 - Docker development environment for CakePHP 15:56 - Middlewares  30:05 - Security 1:31:36 - Performance optimization 2:04:49 - Events   Workshop 2 Michael Hoffmann (Twitter: @cleptric) Topics covered included: 0:00:00 -Setup login action in CakePHP 0:29:10 - Vite with hot reloading Vue.js tailwind css   Workshop 3 Mark Story (Twitter: @mark_story) Topics covered included: 0:04:25 - Leveraging new style fixtures 0:48:26 - Using the DI container 1:30:13 - Browser automation testing with Panther. 2:17:13 - Helpers you may need.
 

Talks:

* Juan Pablo Ramirez (Twitter: @jpramidev) gave the keynote talk on behalf of Passbolt. * Sho Ito (Twitter: @itosho) taught us all about Components * Yuki Kanazawa (Twitter: @yakitori009) and this talk about Automatically Distributing Reference Queries to    Read Replica in CakePHP4 * Mark Scherer (Twitter: @dereuromark) schooled attendees on IDE in CakePHP development * Jiri Havlicek (Twitter: @Jerryhavl) played a big role in fighting COVID-19 by helping create a  contact tracing app (developed with CakePHP) in Czech Republic * Chris Miller (Twitter: @ccmiller2019) explained standards and why we use them * Kevin Phifer (Twitter: @lordsimal)  joined in to explain how to re-use code - utility classes and PHP namespaces * Paul Henriks created a plugin with attendees LIVE * Ed Barnard (Twitter: @ewbarnard) brought the dragons! He talked about finding the Joy in Software Development * Chris Hartjes (Twitter: @grmpyprogrammer) delivered a Grumpy Programmer's Guide to being a senior developer  * Joe Ferguson (Twitter: @joepferguson) shared his knowledge on Modern Infrastructure as code with Ansible * Timo Stark (Twitter: @linux_lenny) shared details about NGINX Unit - and how to modernize your CakePHP deployments

Trivia and giveaways 

Cake ceremony dedicated to Mark Story

We took this time to thank and acknowledge Mark Story for all of his hard work and dedication that he puts into CakePHP. He then headed the cake cutting ceremony (virtually of course) as speakers and attendees enjoyed their own treats!   See the full archive here: https://cakefest.org/archive/virtual-2021  

So what’s to come? 

First!  Videos are starting to be released. With the help of community member Aroop Roelofs, we will be releasing these videos faster than expected. Ticket holders have been receiving access, and they will be released publicly in the coming days.  In regards to future events, it’s up in the air. We will have some internal discussions about safety measures and restrictions, then we will weigh the option between another virtual or physical event. We will, of course, reach out to the community for their input.  I will close by just saying THANK YOU. Thank you for making my job worth it. When an event runs smoothly and gets so much great feedback, that is a direct reflection from the community support. We hope you all will continue to join us in years to come!    Thanks for baking!  

Dependency Injection with CakePHP

Let’s talk about Dependency Injection!

SOLID principles

As you know SOLID is an acronym for the  five object-oriented design principles. In this topic, we will focus on Interface segregation principle and Dependency inversion principle. Interface segregation principle states that a client must not be forced to implement an interface that they do not use, or clients shouldn’t be forced to depend on methods they do not use. In other words, having  many client-specific interfaces is better than one general-purpose interface. From the other side, Dependency inversion principle states that objects must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions. To follow Dependency inversion principle, we need to construct low-level modules and pass them to constructors, and that might create a lot of manual work for developers. The dependency injection container is created specifically for solving the problem with manual construction of an object, before creating a specific object. If we follow interface segregation principle when developing application modules, it would be easy to configure a container and switch module dependency. This is where the interface shows its incredible power.  

Few words about CakePHP Events System

CakePHP Events System was created to allow injecting some logic using listeners. However, in some cases, it is used to get results from code that will be created by the module user. When an event is dispatched by the listener, it can return the result. Callback injection through the event system has some drawbacks. First of all, parameters passed to the event need to pass as a hash array. So unfortunately, there is no way to check that all params are really passed or to be sure that all passed params have correct types. Is there a way to solve this problem? Yes, and containers could help with that. Instead of passing events, we can get the required object from the container and call it method. But you could say: wait, we don't know what object could be used in client code within the developed plugin. That's fine, and this  is where interface segregation principle can help. In our plugin, we define an interface for each such case, and instead of dispatching an event, we can easily get an object from the container by interface.       $updater = $container->get(AfterLoginInterface::class);     if ($updater !== null) {         $user = $updater->afterLogin($user);     }   In the Application::services method, users link the interface with the specific class.       public function services(ContainerInterface $container): void     {         $container->add(AfterLoginInterface::class, MyAfterLogin::class);     }   In some of default behavior needed we can map service class for container to default implementation using Plugin::services method.       public function services(ContainerInterface $container): void     {         if (!$container->has(AfterLoginInterface::class)) {             $container->add(AfterLoginInterface::class, NullAfterLogin::class);         }     }  

Container propagation

Dependency injection is an experimental feature. Initial implementation limited by Controllers constructors and methods, and Commands constructors. If we want to access the container in other parts of the application, we may want to propagate it from app level. The most logical way would be to implement middleware and store the container inside the request attribute.   <?php declare(strict_types=1);   namespace App\Middleware;   use Cake\Core\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException;   /**  * Container Injector Middleware  */ class ContainerInjectorMiddleware implements MiddlewareInterface {     /**      * @var \Cake\Core\ContainerInterface      */     protected $container;       /**      * Constructor      *      * @param \Cake\Core\ContainerInterface $container The container to build controllers with.      */     public function __construct(ContainerInterface $container)     {         $this->container = $container;     }       /**      * Serve assets if the path matches one.      *      * @param \Psr\Http\Message\ServerRequestInterface $request The request.      * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.      * @return \Psr\Http\Message\ResponseInterface A response.      */     public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface     {         return $handler->handle($request->withAttribute('container', $this->container));     }   That’s it! I hope that this will help you when you are baking with dependency injections. If you run into any problems, there are many support channels that allow the CakePHP community to help  You can check them out under the community tab at CakePHP.org.

Dependency Injections with CakePHP

Let’s talk about Dependency injection!

SOLID principles

As you know SOLID is an acronym for the  five object-oriented design principles. In this topic, we will focus on Interface segregation principle and Dependency inversion principle. Interface segregation principle states that a client must not be forced to implement an interface that they do not use, or clients shouldn’t be forced to depend on methods they do not use. In other words, having  many client-specific interfaces is better than one general-purpose interface. From the other side, Dependency inversion principle states that objects must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions. To follow Dependency inversion principle, we need to construct low-level modules and pass them to constructors, and that might create a lot of manual work for developers. The dependency injection container is created specifically for solving the problem with manual construction of an object, before creating a specific object. If we follow interface segregation principle when developing application modules, it would be easy to configure a container and switch module dependency. This is where the interface shows its incredible power.  

Few words about CakePHP Events System

CakePHP Events System was created to allow injecting some logic using listeners. However, in some cases, it is used to get results from code that will be created by the module user. When an event is dispatched by the listener, it can return the result. Callback injection through the event system has some drawbacks. First of all, parameters passed to the event need to pass as a hash array. So unfortunately, there is no way to check that all params are really passed or to be sure that all passed params have correct types. Is there a way to solve this problem? Yes, and containers could help with that. Instead of passing events, we can get the required object from the container and call it method. But you could say: wait, we don't know what object could be used in client code within the developed plugin. That's fine, and this  is where interface segregation principle can help. In our plugin, we define an interface for each such case, and instead of dispatching an event, we can easily get an object from the container by interface.       $updater = $container->get(AfterLoginInterface::class);     if ($updater !== null) {         $user = $updater->afterLogin($user);     }   In the Application::services method, users link the interface with the specific class.       public function services(ContainerInterface $container): void     {         $container->add(AfterLoginInterface::class, MyAfterLogin::class);     }   In some of default behavior needed we can map service class for container to default implementation using Plugin::services method.       public function services(ContainerInterface $container): void     {         if (!$container->has(AfterLoginInterface::class)) {             $container->add(AfterLoginInterface::class, NullAfterLogin::class);         }     }  

Container propagation

Dependency injection is an experimental feature. Initial implementation limited by Controllers constructors and methods, and Commands constructors. If we want to access the container in other parts of the application, we may want to propagate it from app level. The most logical way would be to implement middleware and store the container inside the request attribute.   <?php declare(strict_types=1);   namespace App\Middleware;   use Cake\Core\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use RuntimeException;   /**  * Container Injector Middleware  */ class ContainerInjectorMiddleware implements MiddlewareInterface {     /**      * @var \Cake\Core\ContainerInterface      */     protected $container;       /**      * Constructor      *      * @param \Cake\Core\ContainerInterface $container The container to build controllers with.      */     public function __construct(ContainerInterface $container)     {         $this->container = $container;     }       /**      * Serve assets if the path matches one.      *      * @param \Psr\Http\Message\ServerRequestInterface $request The request.      * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.      * @return \Psr\Http\Message\ResponseInterface A response.      */     public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface     {         return $handler->handle($request->withAttribute('container', $this->container));     }   That’s it! I hope that this will help you when you are baking with dependency injections. If you run into any problems, there are many support channels that allow the CakePHP community to help  You can check them out under the community tab at CakePHP.org.

One CakePHP Project Per Day

The whole team here at CakeDC are big supporters and contributors of the CakePHP community. For this month, I decided to do “one CakePHP project per day” to share with the community.  Here are some of my projects so far:

Project 01 - Notes App

A one page note application using CakePHP 4 and Bootstrap 5. This project is  a good starting point to learn the framework. Link: https://github.com/rochamarcelo/one-project-a-day-challenge-01-notes  

Project 02 - Contact List

An application to manage contacts - you are able to list, add, edit and delete contacts, upload contact avatar images or use avatar images from gravatar.com . It was built using CakePHP 4, plugin friendsofcake/search, plugin josegonzalez/cakephp-upload, Gravatar, and Bootstrap 5.  Link: https://github.com/rochamarcelo/one-project-a-day-challenge-02-contact-list  

Project 03 - Recipe Box

An application to manage recipes, using CakePHP 4,  CouchDB and Bootstrap 5. This one is a good starting point to learn to use CouchDB with CakePHP, including how to list, add and edit recipes (documents). Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-03-recipe-box  

Project 04 - Service Plan with Exchange rate

An application to list services and apply exchange rate using the api https://exchangeratesapi.io/documentation/ and CakePHP 4. In this one you see the custom namespace WebService to handle logic related to api as client. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-04-service-plans-ex-rate  

Project 05 - Polls

A fun poll app, using the awesome Bulma CSS Framework and CakePHP 4. A good example of model association and the CounterCache Behavior. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-05-polls-emmy  

Project 06 - Movie Theater Schedule

An application to see which movies are in the theaters and which hours by screen each day of the week. A good example of complex queries, model associations and seed data. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-06-movie-theater-schedule  

Project 07 - Podcast Finder

An application to help easily find podcasts and download episodes. In the source code you’ll find how to use the itunes api,  a structure to handle Model actions (that I think is a good option to make your models cleaner), and a way to parse podcasts feed (XML); example usage of dependency injection. The application was built with CakePHP 4 and Bulma CSS Framework. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-07-podcast-finder  

Project 08 - Url Shortener

An application to create short urls - a good example of how to create custom routes and use custom primary key types for a model. The application was built with CakePHP 4. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-08-url-shortener  

Project 09 - Quiz

Users can list quizzes, create quizzes and answer at any time. A good example of how to use MongoDB with CakePHP 4 with a base structure for Collection classes.  Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-09-quiz  

Project 10 - File Transfer

An application to easily send files to anyone, create an account, upload the file and inform the person email to send to. Built with CakePHP 4, plugin CakeDC/Users,  plugin Josegonzalez/Upload,  plugin friendsofcake/bootstrap-ui, SMTP and Bootstrap. A good example to see the usage of these plugins. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-10-file-transfer  

Project 11 - Tasks

A one page application for  users to manage their tasks. The user can create and remove decks, create and complete tasks, and list tasks grouped by decks. Built with CakePHP 4, plugin CakeDC/Users and Bootstrap 5 Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-11-tasks  

Project 12 - Blog

A blog website with blog posts and tags management, WYSIWYG editor, blog search, tags filtering. Built with CakePHP 4, CakeDC/Users plugin, friendsofcake/bootstrap-ui, Muffin/Slug, friendsofcake/search and Bootstrap 4 . A good example of usage of custom routes, route prefix, finders and multiple plugins. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-12-blog  

Project 13 - Olympic Medal Count

Perfect time for this project, right?! An application to display olympic medal count by country and sports. The source code uses CouterCache behavior and aggregated query. Built with CakePHP 4 and Bootstrap 5. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-13-olympic-medal-count
 

Project 14 - Smart Home Dashboard

An awesome dashboard to manage smart devices using MQTT Messaging, CakePHP 4, CakeDC/Users plugin, php-mqtt/client (testing with Mosquitto Broker) and Bootstrap 5. The application is able to publish messages to change device status and subscribe for status changes. Link: https://github.com/rochamarcelo/one-cakephp-project-a-day-challenge-14-smart-home-dashboard-mqtt    I hope that this initiative will somehow inspire others to put their Cake skills to work, and share their projects with the community. If you’d like to see my future projects and posts, you can follow me on Twitter, and I will share them all there! https://twitter.com/mrcodex

Logging CakePHP Applications To Team C...

The log of applications is gold. It's an important part of the software, they represent the health of the application. By default, CakePHP will use the FileLog adapter which will write to /logs/ folder. It's hard to track the live issues, and by hard I mean you will need to connect to the server, open the file on /logs/ and look at the issue which you want to investigate.   What do you think if your application sends the error directly to your team communication (Slack, Teams, RocketChat) application? Will be easier to know about a new error after some deployment? This error is sneaky, and can be in command applications. Often, we only look at the errors when the users report it.   For this sample I will use Slack, but this approach can be implemented for any application.  All we need is to create a Log adapter and configure it. So…let’s bake that:     Now we may get errors like this:   That’s all bakers! I hope this article can be useful and you can improve your logs.  

A CakePHP Docker Development Environment

We sponsor a monthly CakePHP training session (register here https://training.cakephp.org ) where we cover different topics about the framework. One of our sessions, the "Getting Started with CakePHP 4" is aimed to help developers starting a new project quickly and following the best practices.   Our previous "recommended" quick setting for a CakePHP development environment was using a vagrant box. See details here:  https://www.cakedc.com/jorge_gonzalez/2018/01/17/using-a-vagrant-box-as-quick-environment-for-the-getting-started-with-cakephp-training-session. However, we've switched internally to use docker as our primary development environment and also we started using docker in our training sessions.   Here's a quick overview of a simple docker based development environment for CakePHP.  

1. Create a new CakePHP project skeleton using 

composer create-project cakephp/app myproject   A new folder "myproject" will be created with a CakePHP project skeleton inside. Go to this new directory and proceed.  

2. Create a new "docker-compose.yaml" file with the following contents

version: '3' services:   mysql8:     image: mysql:8     restart: always     container_name: mysql     environment:         MYSQL_ROOT_PASSWORD: root         MYSQL_DATABASE: my_app         MYSQL_USER: my_app         MYSQL_PASSWORD: secret     volumes:       - ./:/application     ports:       - '9306:3306'     cakephp:     image: webdevops/php-apache:8.0     container_name: cakephp     working_dir: /application/webroot     volumes:       - ./:/application     environment:       - WEB_DOCUMENT_ROOT=/application/webroot       - DATABASE_URL=mysql://my_app:secret@mysql/my_app     ports:       - "8099:80"
 

3. Run "docker-compose up"

You'll create 2 containers named mysql and cakephp -  check the docker-compose configuration to see default database and users created in the mysql container, and the same environment params passed to the cakephp container via DATABASE_URL to allow the cakephp container to connect with the mysql database.   NOTE: the ports exposed are 9306 for mysql and 8099 for cakephp webserver. You can list them using docker-compose ps.  

4. Access your database and cakephp shell

  • To access the database you can use the command:
mysql --port 9306 -umy_app -psecret my_app   To restore a database dump for example, you can use the command: curl -L https://raw.githubusercontent.com/CakeDC/cakephp4-getting-started-session/master/my_app.sql |mysql --port 9306 -umy_app -psecret my_app   You can also configure any database tool to access the database in: localhost:9306  
  • To access the cakephp environment and shell you can use the command:
docker exec -it --user application cakephp bash   You'll go to the webroot folder, so in order to run the cake shell you'll need to: cd .. bin/cake 
  Now you have a working environment to play with the training session contents.   In this previous article, we covered another approach to setting up a local docker environment: https://www.cakedc.com/rochamarcelo/2020/07/20/a-quick-cakephp-local-environment-with-docker    We hope to see you in our next training session! https://training.cakephp.org   

Updating Model Layer

One reason to migrate from CakePHP 2.x to newer versions, is the very powerful ORM system that was introduced in CakePHP 3.x.  

Improved ORM Objects

The CakePHP model layer in CakePHP 3.x uses the Data Mapper pattern. Model classes in CakePHP 3.x ORM are split into two separate objects. Entity represents a single row in the database and it is responsible for keeping record state. Table class provides access to a collection of database records and describe associations, and provides api to work with a database. One notable change is afterFind callback removal. In CakePHP 3.x, it is possible to use Entity level getters to provide calculated fields on entity level.  

Association Upgrade 

In CakePHP 2.x associations are defined as arrays properties like this:     public $belongsTo = [         'Profile' => [             'className' => 'Profile',             'foreignKey' => 'profile_id',         ]     ];   In CakePHP 3.x and 4.x associations are declared in the initialize method. This gives much more flexibility in association configuration.     public function initialize(): void     {         $this->belongsTo('Profile', [                 'className' => 'Profile',                 'foreignKey' => 'profile_id',         ]);              }   Or using setters syntax, it could be done this way: public function initialize(): void     {         $this->belongsTo('Profile')         ->setForeignKey('profile_id')     }  

Behavior Upgrade

In CakePHP 2.x, behaviors are initialized as arrays properties:     public $actsAs = [         'Sluggable' => [             'label' => 'name',         ],     ];   In CakePHP 3.x and 4.x,  behaviors are configured in the initialize method. This gives much more flexibility in configuration, as in params it's possible to pass anonymous functions.     public function initialize(): void     {         $this->addBehavior('Sluggable', [             'label' => 'name',         ]);              }  

Validation Upgrade

In CakePHP 2.x, behaviors are  initialized as arrays properties:     public $validation = [         'title' => [             'notBlank' => [                 'rule' => ['notBlank'],                 'allowEmpty' => false,                 'required' => true,                 'message' => 'Title is required'             ],         ],     ];   In CakePHP 3.x and 4.x, validation is defined in validationDefault method which builds validation rules.     public function validationDefault(Validator $validator): Validator     {         $validator             ->scalar('title')             ->requirePresence('title', 'create')             ->notEmptyString('title');           return $validator;     }   Additionally, CakePHP introduced the buildRules method, which is where  described foreign keys constraints, uniqueness, or business level rules.     public function buildRules(RulesChecker $rules): RulesChecker     {         $rules->add($rules->existsIn(['user_id'], 'Users'));         $rules->add($rules->isUnique(['username'], __('username should be unique')));                            return $rules;     }  

Finder Methods

In CakePHP 2.x, the custom finder method is called twice - before and after fetching data from the database, which is defined by the $state parameter. Parameter $query contains current query state, and in $results passed data returned from database.     protected function _findIndex($state, $query, $results = array()) {         if ($state == 'before') {             $query['contain'] = ['User'];         } else {             // ...         }     }       In CakePHP 3.x, custom finder method accepts query object and some options passed from client code and returns an updated query. This allows for combining multiple finder methods in the same call, and has better grained finder logic.     public function findIndex(Query $query, array $options): Query     {         return $query->contain(['Users']);     }   The afterFind method could be implemented with the Query::formatResults method, which accepts an anonymous function to map each collection item.

Why Database Compression?

Nowadays people are not concerned about how large their database is in terms of MB. Storage is cheap. Even getting cheap SSD storage is not a big deal.    However, this is true if we are talking about hundreds of MB or even several GB, but sometimes we get into a situation where we have massive amounts of data (i.e Several tables with lots of longtext columns). At this point it becomes a concern because we need to increase the hard disk size, and find ourselves checking to see  if the hard disk is full several times per day or week, etc.   Now, if you have faced a situation like this before, it's time to talk about database compression. Compression is a technique, developed theoretically back in the 1940s but actually implemented in the 1970s. For this post we will focus on MySQL compression, which is performed using the open-source ZLib library. This library implements the LZ77 dictionary-based compression algorithm.   Before going into MySQL compression details, lets name some of the main DBMS and their compression techniques:

  • MySQL: ZLib (LZ77) [1]
  • Oracle: Oracle Advanced Compression (Proprietary)[2]
  • Postgres: PGLZ or LZ4 (if added this option at compilation level) [3]
  • DB2: Fixed-length compression or Huffman in some systems [4]
  So, now that we know this useless information, lets learn how to implement this in MySQL.   Firstly, you need to know that you CAN'T enable compression if:
  • Your table lives into `system` tablespace, or
  • Your tablespace was created with the option `innodb_file_per_table` disabled.
  It is important to test if the compression is the best solution for you.  If you have a table with a lot of small columns, you will probably end up with a larger-size table after "compressing" because of the headers and compression information. Compression is always great when you have longtext columns which can be heavily compressed.   Then, to enable compression for a table, you just need to include the following option when your table is created, or execute it as part of an alter statement: ROW_FORMAT=COMPRESSED These are the basics but you may find more useful information in MySQL manual.   You can also take a look at Percona which implements a Column level compression. This is interesting if you have a table with a lot of small fields and one large column, or if you have to optimize your database as much as possible. [6]   Finally, just say that even that storage is cheaper than ever, the amount of information has increased as well and we are now using and processing an incredible amount of data... so it looks like compression will always be a requirement.   I hope you find this information useful and please let me know if you have any questions or suggestions below in the comments section.

  [1]:https://dev.mysql.com/doc/internals/en/zlib-directory.html  [2]:https://www.oracle.com/technetwork/database/options/compression/advanced-compression-wp-12c-1896128.pdf  [3]:https://www.postgresql.org/docs/devel/runtime-config-client.html  [4]:https://www.ibm.com/docs/en/db2-for-zos/12?topic=performance-compressing-your-data  [6]:https://www.percona.com/doc/percona-server/8.0/flexibility/compressed_columns.html

Migrate CsrfComponent to CsrfProtectio...

The CsrfComponent was deprecated since CakePHP version 3.5.0. On CakePHP 4, we now have a new middleware to help us protect applications against Cross Site Request Forgery attacks. In this article, we are going to show the different ways to enable and disable Cross Site Request Forgery between the controller and the new middleware.  

Enable CSRF

Do these changes:
  • In your Application::middleware add $middlewareQueue->add(new CsrfProtectionMiddleware());
  • Remove $this->loadComponent('Csrf') from your controllers.
The configuration keys from CsrfComponent cookieName, expiry, secure and field are also available in the middleware. If you used any of these, you should be able to continue using the middleware.  

Disable CSRF

Is not recommended to disable CSRF, but sometimes you really need to. With the component you could have something like this in your controller:   Now with the middleware, we can use the method skipCheckCallback to disable Csrf based on a custom logic:     That’s it, we have migrated CSRF protection from CsrfComponent to CsrfProtectionMiddleware.  

CakePHP Upgrade to 4 - Piece by Piece

Let's imagine you have a huge application in CakePHP 2.x (or 1.x) and you're planning to upgrade to the latest CakePHP 4.x. After doing some estimations, you realize the upgrade process is out of your scope, because you don't have the budget or developer availability to do it in 1 shot. At this point, some companies would abort the upgrade and keep working on 2.x for "some more time" until "this last release is delivered" or until "budget is available next fall", digging deeper and deeper into the rabbit hole…   There's an alternative you could follow if this is your case: proceed with the upgrade of a smaller portion of your application and let the 2 versions coexist for some time.   Warning: This is NOT for every project or company. Please carefully think about this decision as it has overhead you'll need to handle.   So, if your application has a portion that could be extracted, with a small set of dependencies from other areas of your application, or if you are creating a new feature with a limited set of dependencies with the rest of your application, this approach would be good for you.   In order to allow both applications to coexist, we are going to keep the CakePHP 1.x application as the main one, and use CakePHP 4.x as a subfolder inside of the first one. It's important to note that in order to share sessions between both applications you'll need to use a storage you can actually share, like database or cache based sessions (redis, etc). Then, you can use a configuration like this one (see below) to add a new upstream to handle your new application. Note: the upstream could be located in another server of your network, using a different PHP version etc.   We've used nginx as an example, but you can use the same approach in other web servers like Apache.   In our example we're going to use all paths starting with /api  to be managed by our new CakePHP 4.x application. upstream cake4 {      # Note this could be any server/port in your network where the cake4 application is installed          server 127.0.0.1:9090; }   # This is our CakePHP 2.x server server {     server_name example.com;       root   /var/virtual/example.com/app/webroot;     index index.php;       # All requests /api are forwarded to our CakePHP 4.x application location /api {         proxy_pass http://cake4;             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;         proxy_set_header Host $host;             proxy_http_version 1.1;         proxy_set_header Upgrade $http_upgrade;             proxy_set_header Connection "Upgrade";     }       location / {             try_files $uri $uri/ /index.php?$args;     }       location ~ \.php$ {           try_files $uri =404;           include fastcgi_params;                fastcgi_pass unix:/run/php/php7.4-fpm.sock;           fastcgi_index index.php;             fastcgi_intercept_errors on;         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;     } }   # This is our CakePHP 4.x server server {     listen 9090;     server_name example.com;       root   /var/virtual/cake4-example.com/webroot;     index index.php;       location / {         try_files $uri $uri/ /index.php?$args;     }       location ~ \.php$ {         try_files $uri =404;             include fastcgi_params;         fastcgi_pass unix:/run/php/php7.4-fpm.sock;             fastcgi_index index.php;         fastcgi_intercept_errors on;             fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;     } }   As you can see, we have 3 blocks defined in our configuration file:

  • upstream cake4 {...} to forward requests to the CakePHP 4.x application
  • server {... 2.x ...} using a location /api to forward all these calls to the CakePHP 4.x server
  • server {... 4.x ...} using a specific port (9090) to handle requests in CakePHP 4.x
  Using this approach, you can break your application into 2 parts, and start moving features by path to CakePHP 4. You'll need to handle the changes in 2 projects for a while, and pay this overhead,  but this could be better to maintain than a CakePHP 2.x application sitting on an old PHP version. Happy baking!  

Dependency Injection with CakePHP

Dependency Injection is some of the bigger buzzwords in PHP frameworks.  Historically, CakePHP application logic didn’t support that, until the version 4.2 was released last December. You can do that on your own and have a few plugins for that. This is a new chapter of the framework, let's see how to bake it.  

Use Case

First, let’s talk about a classic Use case on real applications. Our application will include an address form, such as the shipping address for an online order, or provide information about User, Company, etc. Autocomplete can help users supply the details.   We will use the Geocoding API from Google Maps Platform, making a HTTP request for API with json output format and address parameter: https://maps.googleapis.com/maps/api/geocode/json?address=89104&key=****** And here we go, we will get this result:  

Baking a Address Service

After seeing the Use case, all we need on our backend is to make a HTTP request for API and return the JSON result for the frontend to populate related fields.   1. First, let’s exposing our application for accept “.json” requests:   2. Now, we can bake a Address Controller and let’s request an empty result: $ ./bin/cake bake controller Address --actions index   Now our app requests /address.json will return an empty JSON.   3. Let’s bake (manually) the Address Service:   Basically I’m using Cake\Http\Client to make the API request. Also I read Geocode.key from Cake\Core\Configure, we don't want to expose our key on public requests (add the key on config/boostrap.php).   4. Let’s rewrite our Controller:   5. Finally, let’s add our Service on Application.php:   That’s all bakers! Now our endpoint /address.json will support query parameters and return the result of the API request.  

The cost of shiny

I’m here selling an idea and I don't start with the cons. Unfortunately, the Dependency Injection container is an experimental feature that is not API stable yet.  The support is a bit limited, CakePHP will inject services into: constructors of Controllers and Commands and Controller actions. The core team hopefully stabilizes the feature on version 4.3, or at most 4.4. They need your help testing and finding cases, and feedback always is welcome.   I hope this post can be useful for you and your projects.  See you next time!  

We Bake with CakePHP