CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

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.

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!  

Planning For Your Upgrade

Having a successful upgrade implies not only upgrading the code itself, but also identifying the different tasks that will be part of the Upgrade Plan. Making a good plan for an upgrade requires identifying the current status of the application. A good plan is based upon clear, well-defined, and easily understood objectives.   After years of experience with CakeDC making upgrades, migrating applications from CakePHP 1 to CakePHP 4 in all possible combinations, we have noticed there are a set of elements or characteristics that are useful to evaluate and identify before starting the upgrade. Having a clear understanding of these elements will be helpful to define the different tasks that will be included in the Upgrade Plan, and reduce any risk while upgrading and delivering.   Imagine that you want to run a marathon - but before starting any of the thousands of plans you can find on the internet about “How to run a Marathon”, you must know where you are. You could ask yourself:  How many miles per week are you currently running? What is the base training needed to start this program? What is the distance of your longest run in the past 3 weeks? How many days per week do you have available to exercise?, etc. This will help you to choose the plan that better fits you. It’s important to identify where you are, where you want to get and how to get where you want.    Wondering how  to evaluate where you are for the Upgrade? Evaluate the status of your application. You could consider the following points as reference:

  • What is your current CakePHP version? 
  • Identify the weaknesses and the strength of the current code by making a code review.
  • Identify the versions of the packages, plugins, libraries that your application is using. 
  • If you are using CakePHP Third Party plugins, figure out if those plugins have already been upgraded.
  • Identify any third party integration and how the upgrade could affect it. 
  • What is the unit test coverage, if any? 
  • Is there any existing documentation?
  • Is there any custom change in the CakePHP core? (I hope there is not!)
  The complexity, time, cost, and resources required to upgrade your application will depend on the status of your application. Once you know where you are, it’s the time to plan how to get where you want.  Let’s talk about this in a future article. In case you are looking for some guidance on preparing your Upgrade Plan, don’t hesitate to contact us, we could help you to identify your current status, define the plan and execute the whole plan for you. We can also work together with your team on the upgrade, helping them understand the upgraded codebase so you can maintain the project with your own team as you did before.  

Modifying Requests Like A Chef

Since the version 2.x of CakePHP has a requests and response objects, they are provided an abstraction around HTTP Requests and responses. If you are not familiar with CakePHP, it’s a common step when you bake and use $this->request->data instead of $_POST. Most of the time, we need to modify and append values on our Request data. This can be an identifier of logged user or values for any fields. In many situations, implementations will like this: Data can be modified easily - you just need to call withData or withParsedBody method and after set the Request  (you can also modify the query calling withQueryParams): Both implementations will generate the same value, but if you have a keen eye, you will see that the second implementation is more clear. Also, our Request has these values on data. This information can be useful when you use Components from Plugins, as they will expect the values on Requests.   That’s all bakers! I hope this content is useful for you and will improve your requests!  

Where you SHOULD be marketing your bus...

Marketing is an essential part of your business’ success. I don’t just say this because I myself am a marketing connoisseur... or maybe I do. But either way, I’m going to shoot you some quick knowledge about getting your name out there... specifically into the cyber world.   

Social media 

Branding is very important here. This will be another blog for another time... but having a uniform look, format, font, etc will help you look professional and stand out. Some of the platforms I work with for our company is Facebook, Instagram, Twitter. In our industry, Twitter is our cake and frosting (see what I did there). Most developers have a Twitter and use this to interact with other developers, frameworks, and companies. Having a company page allows you to engage with your followers, have conversations, and build relationships. Remember, you need to be posting things that are important for those who follow you to see, and when they reach out, be ready to respond.  For business contacts and networking, I am a big fan of LinkedIn. This platform is an easy way to connect and search for others in your field. Also, it's a good way to find people looking for your specific services. Very business. Very professional.  You definitely need to get to know your audience. Tracking your social analytics will tell you where you stand out most. Then, you utilize that information!  

Ads

 I’m a fan of Google Ads. While I know that the idea of paid advertising isn’t ideal or financially possible for everyone, there are other options. Keeping up with your SEO, or search engine optimization, will help with organic ads. Organic ads is a fancy way of saying free clicks, or free adveritsing. When people are searching Google for services or phrases pertaining to your business, then your site will show in the results. Obviously if you pay for ads, you can manually add phrases and terms that may be searched for... and these are called keywords. I think Google Ads pointers may be a good blog for me to share in the future *makes mental note*.    Speaking of Google, make sure your “my Google business” account is up to date, otherwise you will literally NEVER show up on the search engine. Even when someone specifically searches for you or your company.   

Email Marketing

We must be careful here. Gone are the days of spam emailing... and cold calling? Please don’t. I’d say most people are ready to get restraining orders against telemarketers. Just me?  However, if you have specific things (sales, offers, important news) to share with your customer base, then by all means - onward. At least emails can be ignored if they are unwanted. If you want your email to be opened, make sure that you are offering your recipients something worth clicking (specials. Giveaways. Etc.). A good platform to help you with this is MailChimp, but there are soo many ways to generate these emails, and many even offer pre-made templates... so no excuses.   

Newsletters

Similar to email marketing, there are newsletters. The difference here is that the people who will be receiving your monthly (most likely) newsletter are only those that have chosen to. “Subscribers” sign up to receive these emails. Usually, these aren’t offers of sales, but rather news, events, tips etc. You can get an idea of what I mean by checking out the CakePHP Newsletter archives. 
  So let's close with some quick facts: Newspaper advertising? Out Telemarketing? Out  Print? Maybe  Billboards? If the price is right and you are local to certain areas. International companies, like CakeDC do not benefit from this type of print, unless we could put one in every city around the world. I think that would blow my marketing budget pretty quick.  If you are a freelancer, I definitely suggest Fiverr. Let people find you. Essentially you get quality leads for free.    All of these marketing platforms and items need to be explained in deeper detail, so if you have any questions feel free to reach out to me!  

Benefits Of Upgrading

Let’s talk more about upgrading your CakePHP application. In last week’s blog, we talked about why you should hire externally for all of your upgrade needs. You may have been thinking… but why would I (or my company) even need to spend the time, effort, and money on upgrading our projects. Well… for many reasons. You need better security, compatibility, functionality.  You’ve seen our posts, you know what needs to be done. Your old CakePHP application needs to be updated.  I want to remind you about some of the benefits that there is to upgrading.   

SECURITY

The more maintained a CakePHP version is, the more security it can provide. This not only protects the projects themselves, but can also give you peace of mind knowing that the latest versions will be functional a lot longer than say CakePHP 2.x. And of course, the latest releases fix a number of security issues. No company wants to offer quality services to their customers,  and end up with a security breach that was out of their control. It is extremely important to get ahead of the security issues on the front end. Be proactive, and you won’t have to be reactive.  The biggest concern is that many hosting providers are abolishing old PHP branches, essentially overnight. This is why it is important to be aware of when to migrate/upgrade and do it before it is too late. You can see a list of the end of life date for each unsupported branch of PHP HERE.   

PERFORMANCE

CakePHP 4 follows the latest conventions, helping your application run faster and smoother. Old sites / applications run slow… that is no secret. I promise you one thing, today’s Google searcher will not think twice to do a different search if the site is lagging (ain’t nobody got time for that).  Also, migrating to a current PHP release over 5.6 and using the new ORM, could lead to improvements over 50%. So I mean, win-win.    If you are wondering about your performance, speed, or  which versions of PHP you are running on, you can use tools like Pingdom - https://tools.pingdom.com/ or Google Chrome Devtools - https://developers.google.com/web/tools/chrome-devtools.  

SCALABILITY & TOOLS

CakePHP 4 is shipped with best practices to streamline horizontal scaling and deployment into containers. As new tools and plugins are released, they may only be compatible with the latest versions. Currently, there are over 900 updated plugins, see here: https://plugins.cakephp.org/, covering from background job processing, image processing, CMS, file upload and management, cache, and more. This provides more features and results in developers WANTING to use and work with the framework. 

Of course there is a long list of additional benefits, but these are some of the most important. 2021 seems to be turning into the year of upgrades. Don’t get left behind!

Why You Should NOT Upgrade Your CakePH...

There are many reasons that CakePHP recommends upgrading. But should you, really? Contrary to what you would expect, I am here to tell you that maybe you should not upgrade your application. WHAAAAAAT? I said what I said. The answer is no… but yes, the application should be upgraded. What do I mean? I mean that SOMEONE should upgrade to CakePHP 4, but that someone should not necessarily be you or your team.  Let’s be real… upgrading takes time. It will take priority and focus. Is extra time something your team has? Usually not. This is why I suggest outsourcing for any upgrading.   

Prioritization

Perhaps your team is extremely busy with internal work, and you just can't fathom the idea of utilizing your resources on a time consuming project, such as upgrading. I would imagine that it’s not an easy task to go to your CEO / IT manager and explain why you were unable to meet a deadline due to unexpected complications during a migration. This is one reason that it would be beneficial to hire a team. Then, you are able to keep your team working on tasks that actually add value to your business, providing the best service for your customers…. What I am trying to say is let us doing the boring tasks of upgrading    

No Training / New Skills

Even if a junior level developer was tasked with upgrading one or all of the company's projects, why pay for their time when it is not advancing them in any way? During an upgrade, the tedious work is not resulting in any new skills for the developer. There is no training, or development skills to be learned during an upgrade process. This is a huge factor for a lot of CakeDC’s upgrade clients. The money and time spent for doing these actions internally does not provide long term gains. For us - we need to know the ins and outs of upgrading, and we can prioritize these items for our client work. We actually learn from each migration that we do and we can utilize those skills in future upgrades.    

Hire A Team

Obviously, I am going to tell you to hire CakeDC for upgrading, but truthfully that is because we have done many upgrades (and learned the mistakes / solutions to many problems that occur) and have well experienced developers in most time zones  This allows us to have great relationships with our clients, and stay in constant contact. The biggest benefit is that hiring externally will not disrupt your routine, and it gets the upgrading / migration done a lot quicker. We are all tempted with distractions, prioritized work, etc. Save time, and probably money by looking into a company to do the work for you, and I promise you will thank me later.    Another shameless plug: see our development service details HERE. Need more reason to upgrade? Check back to read next week’s blog for the many benefits.   

CakeFest 2021 Decisions

Well… 2021 is already feeling a little 2020ish to me, what about you? While I had high hopes of things being back to normal as far as travel, events, etc. It seems as though we still have a ways to go in that department.  

Difficult Decisions

Our events are no exception to this. While virtual CakeFest was a great success, I think that the CakePHP team, as well as the community had hoped for an in-person event… sooner, rather than later. Everyone is missing the adventures and camaraderie that physical meet-ups bring. Unfortunately, we may be waiting a little longer. The team couldn’t stand to make the tough call on the event alone, without consulting with the community.  

The Community Has Spoken

So, CakePHP took to the polls. The question was posted via social media, and included in the January newsletter: Should CakeFest be virtual or in-person (Los Angeles, specifically)? The consensus was no surprise, and 85%+ of bakers voted for a virtual event this year. One follower mentioned that he “wasn’t ready to risk the event not happening at all, so a virtual event is better than no event”. I couldn’t agree more.    A virtual conference was uncharted territory for CakeFest planners and attendees, but in my opinion.. it came together so wonderfully, that it is hard to be disappointed that it will be happening again. So here’s to gathering once again from the comfort of your own space, and hoping that everyone remembers to have their cake ready! Mark Story can even (virtually) cut it for you if you prefer.   The call for sponsors and speakers will be opening soon, so make sure to contact the CakePHP / CakeFest team with any questions you may have ahead of time.  Planning on attending? We would love to hear from you! What are some topics that you would like covered in the workshops or talks? EMAIL US HERE.   *Digital hug*  

Baking Smarter, Not Harder in 2021

After the year we had… our new motto should be work smarter, not harder, in 2021? Am I right? Luckily, CakePHP community and core members are extremely helpful and constantly working to make baking easier. Here are some things that will assist you with your CakePHP projects….

Plugins:

I recently wrote a blog featuring some of the best (voted by the community) CakePHP plugins - you can see it HERE. A full catalogue of CakePHP plugins is available at https://plugins.cakephp.org. It is no secret that plugins are essential for developers. CakeDC has a few of our own as well, you can get details at:  https://www.cakedc.com/plugins. The good news is, if you don’t see one, but have a great idea, you can build and release your own! To learn more about this process, Jose Gonzalez explains it in his CakeFest 2021 Talk.     Lots of other videos / talks / tutorials are located in the CakePHP Youtube channel as well.
 

Tools:

If you follow us on social media, we highlight a lot of tools released from the community.  One of the most popular is the debugging tool: https://book.cakephp.org/4/en/development/debugging.html A commonly used one is to help updating your composer.json while upgrading https://toolbox.dereuromark.de/utilities/upgrade   You can see more on THIS cakePHP tools list from Dereuromark!
 

Support:

I talk about support channels a lot… because well… what is open source without them? Every time I take a virtual stroll to the slack channels, I am amazed at the participation and interaction between community members. It’s like having your own development team available anytime you need them. Rest assured that if you have an issue that's causing a blocker, someone in the chat will (most likely) have a solution. A full list of support channels was listed in our last blog, but if you missed it, here you go: Discourse forum: https://discourse.cakephp.org Stack Overflow: https://stackoverflow.com/tags/cakephp IRC: https://kiwiirc.com/nextclient/irc.freenode.net#cakephp Slack: https://cakesf.herokuapp.com
 

The Book:

If you’re a veteran baker, you already know this. However, this wouldn't be a helpful blog without mentioning the all mighty book… The CakePHP bookThis is where you should start on your cake journey… read it… read it again. Then, reference back to it when you need it. There is an average of 46k users utilizing the book monthly (184k sessions). That should speak for itself.
 

Newsletter:

The CakePHP team releases a newsletter each month. This is a good resource if you’re looking to catch up on a month’s worth of news in one place.  Usually included is: releases, helpful tools, training/event dates, specials, surveys, and more.  You can see previous newsletters & subscribe HERE.   I will close this with a shameless plug: if you want to work a whole lot smarter this year, let someone else do the work for you. Check out all of the CakeDC services offered at cakedc.com/services.    Here’s to 2021 being a lot easier… more peaceful… and tasty!  

Saying Goodbye To 2020 Is A Piece of Cake

I never thought that I would be so excited to say… the year is coming to an end. What a year it has been. Let’s focus on some good things that happened for us this year.

CakePHP Community

Our team worked as closely as ever with the CakePHP community. We have hosted training sessions and multiple online meetups - for which we had consistent attendance and involvement. We have enjoyed getting to know each baker that attends and interacts with us. It was a great year for releases, too. If you follow the social media pages, you’re up to date with all of the new features and tools that are released in real time. Not to mention new and updated plugins. You can see all of the latest releases in the BAKERY.  

CakeFest

While we usually get to travel to some amazing city in the world and meet with the attendees in person, clearly that was not going to be an option this year. For the first time ever, the event was held virtually. Being so involved, and responsible for the success of the event, was stressful and frightening to say the least, but alas…it came together wonderfully.  We were able to have attendees that may not have been able to join us otherwise, and the participation was unprecedented. I am so thankful for the wonderful sponsors, speakers, attendees, and contributors that made the event possible.  In case you didn’t know, all of the CakeFest 2020 videos have been released. You can view them in the CakeFest archive, or on the CakePHP Youtube channel. Don’t forget to subscribe to the channel, and I will tell you why later.    Now… what can be expected in 2021? LOTS!

Increased Involvement

We want to expand the kitchen, if you will. We have an amazing group of core developers, and they would love to have more involvement from the community. If you’ve ever thought about contributing and getting involved, there are many options, you can check out details HERE.   

More documentation / blogs

Speaking of getting more people involved, this will include blogging. We have so many great plugins, but maybe not enough documentation to support the training on them. The core team is on board and we will all be working hard to provide more documentation for the framework. In fact, we even some some community members that have already volunteered to provide more blog contributions to the bakery. Maybe you’d like to as well?!  

Video Tutorials

One suggestion that we get consistently is that we need more video tutorials. We agree! We are going to be updating our YouTube channel and will hopefully be adding more video tutorials as soon as Q1. We will also make sure that training sessions / meetups will be available to subscribers for playback. We would love to hear your suggestions for content, you can email us at community@cakephp.org and let us know what you’d like to see. 
 

Support

As always, CakePHP has many support channels, and this will not change in the new year. In fact, we plan to make it even easier to connect with other bakers.   Here are some current available support options: Discourse forum: https://discourse.cakephp.org Stack Overflow: https://stackoverflow.com/tags/cakephp IRC: https://kiwiirc.com/nextclient/irc.freenode.net#cakephp Slack: https://cakesf.herokuapp.com
  Want to have your opinion heard? The core team wants to know what you want for CakePHP 5. Please take a moment and fill out a quick SURVEY to let them know.    We can’t wait to bake with you in 2021. Wishing you all a happy holiday season and a very happy new year!  

Baking With Attributes

Tasting the cake with attributes

Attributes is a declarative way to pass information about the behaviors of various elements like classes, methods, properties, and even method parameters in your programs. In fact, attributes are used for adding metadata to existing code, and could be used as a way to reduce visual debt, and this way simplifies how code looks like.  

Defining an attribute

An attribute is simply an object whose class inherits from the Attribute class. However, attributes are not used in the same way as a typical object. They often add some additional semantics about the class or method, or to toggle behavior on or off. Some attributes specify functionality. For example, an attribute may contain a method that defines security behavior.  

Declaring Attributes

The attribute itself may be declared as a class. This is validated only when the attribute is fetched, and not immediately when the code is parsed. A PHP attribute is a class, declared with #[Attribute] attribute. In the following example we define an attribute class which allows us to specify what methods are allowed for controller actions.     Take note that in PHP 8 you can declare properties directly in class constructors, which is really handy for data classes.
 

Consuming reflection API to define meta behaviors

Just defined attributes have not added new code logic. To add new behavior we should implement it. Attributes could be fetched using the reflection API. PHP engine knows about attributes but does not instantiate it’s classes, so we have to do it ourselves. Reflection provides getAttributes() methods to fetch a list of associated attributes.   The following  example shows how we can add permissions checks for controller actions using attributes. In this example, the code is stored in beforeFilter of the controller class itself, but it could be an AppController or more generic solution.    

Where to use Attributes

Here are some areas where web frameworks could use attributes:
  •  Routes definition for the controller methods;
  • Validation rules as attributes for entity properties;
  • Smart object serialization, which defined as properties attributes
  • Security rules defined for classes and methods.
  • Static code analyzers.
  • IDE code hinting.
  The attributes are very handy and powerful, they could reduce visual debt and improve code quality. Hopefully this helps with your future projects!  

We Bake with CakePHP