CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

A Quick CakePHP Local Environment With Docker

CakePHP and Docker

We all know that while developing a CakePHP software, we need to have a local environment with PHP, HTTP Server (nginx, apache) and a database (MySql, Postgres, Mongodb, etc). Installing those tools directly to your system is the basic way, but it can become a bit tricky when we have multiple projects using different versions of those tools... that’s where Docker will help us. In this article, we will show a quick docker setup to improve our CakePHP local environment.

If you don’t have docker installed go to: https://docs.docker.com/get-docker/. It is available for Linux, MacOS and Windows.

For our setup we are going to use PHP, Nginx, and Mysql. All of the information required will be added to a new file named docker-compose.yml. In our environment we will need two docker images [https://docs.docker.com/engine/reference/commandline/images/], one image for php + nginx and one for mysql. 

 

Setup Nginx + PHP service

Create the file  docker-compose.yml inside your application with this: 

 

version: "3.1"

services:

  php-fpm:

    image: webdevops/php-nginx:7.4

    container_name: myapp-webserver

    working_dir: /app

    volumes:

      - ./:/app

    environment:

      - WEB_DOCUMENT_ROOT=/app/webroot

    ports:

      - "80:80"

 

Now,we have a service named php-fpm, which is able to run php 7.4 and nginx at port 80 pointing to our webroot dir. Important note: the container_name must be unique in your system. 

 

Setup MySql service

Our MySql service requires a username, password and database name. For this, we are going to create the file mysql.env (don’t use a weak password in production, you could share a mysql.env.default file with your team) with this content:

 

MYSQL_ROOT_PASSWORD=password

MYSQL_DATABASE=my_app

MYSQL_USER=my_user

MYSQL_PASSWORD=password

 

Now, at the end of docker-compose.yml , add this: 

 

  mysql:

    image: mysql:5.6

    container_name: myapp-mysql

    working_dir: /app

    volumes:

      - .:/app

      - ./tmp/data/mysql_db:/var/lib/mysql

    env_file:

      - mysql.env

    command: mysqld --character-set-server=utf8 --init-connect='SET NAMES UTF8;'

    ports:

      - "3306:3306"

 

Before we start this service, lets add the service for our database, include this at the end of the file:  docker-compose.yml .

You’ll see that we have - ./tmp/data/mysql_db:/var/lib/mysql, this allows us to persist mysql data. Now we also have a service named mysql with one empty database named my_app and a user name my_user.
 

Starting the services and app configuration

Before we continue, make sure that you don’t have any other http server or mysql server running.

Now that we have finished our docker-compose.yml  we can execute docker-compose up to start the services and access the app at http://localhost. The next thing you need to do is update your database configuration with the correct credentials - the host is the service name, in our case it is “mysql”:

 

'host' => ‘mysql’,

            'username' => 'my_user',

            'password' => ‘password’,

            'database' => 'my_app',

 

That’s it! Now we have a working local environment for our CakePHP app. We can now access the services using docker-compose exec php-fpm bash  and docker-compose exec mysql bash

The files mentioned here (docker-compose.yml and mysql.env) can be found at  https://gist.github.com/CakeDCTeam/263a65336a85baab2667e08c907bfff6.

 

The icing on the cake

Going one step further, we could add some alias (with linux) to make it even easier. Let’s add these lines at the end of your ~/.bashrc file:

 

alias cake="docker-compose exec -u $(id -u ${USER}):$(id -g ${USER}) php-fpm bin/cake"

alias fpm="docker-compose exec -u $(id -u ${USER}):$(id -g ${USER}) php-fpm"

alias composer="docker-compose exec -u $(id -u ${USER}):$(id -g ${USER}) php-fpm composer"

 

With those entries, instead of typing docker-compose exec php-fpm bin/cake, we can just type cake. The other two aliases are for composer and bash. Notice that we have ${USER}? This will ensure that we are using the same user inside the services.

 

Additional information

Normally docker images allow us to customize the service, for webdevops/php-nginx:7.4 - you can check more information at: https://dockerfile.readthedocs.io/en/latest/content/DockerImages/dockerfiles/php-nginx.html and for mysql check: https://hub.docker.com/_/mysql . You can find more images at: https://hub.docker.com/.

If you are not familiar with docker, take a look at: https://docs.docker.com/get-started/overview/, as this documentation provides good information.

 

Hope you have enjoyed this article and will take advantage of docker while working in your CakePHP application.

 

Latest articles

Playing with the new CakePHP Queue

One of the topics discussed in the community is the benefit of a unified, officially supported, CakePHP Queue plugin. Queues are used in most of the projects nowadays and are a central utility plugin. During the CakeFest 2020 event, there were also a couple direct references from speakers: (https://speakerdeck.com/josegonzalez/building-and-releasing-a-cakephp-plugin/?slide=15c) and this comment from Mark Story: https://cakesf.slack.com/archives/C172CS4TE/p1602257791377500.   This motivated me to take a deeper look at the cakephp/queue plugin and write this blog post.   Here at CakeDC we've been using queues for a looooong time. Initially in CakePHP 2, we've used plugins like CakeResque with redis or custom workers tied to Amazon SQS queues. Then in CakePHP 3 & 4 we've been using mostly https://github.com/josegonzalez/cakephp-queuesadilla with redis or mongodb backends. https://github.com/cakephp/queue   First thing would be setting up the plugin in your project, we are going to use the example project we used in CakeFest 2020: https://github.com/cakephp/cakefest2020/#using-docker   So after setting up the project and running it via docker compose, we can proceed to setup the plugin via composer. We will need to add it as a repository and set  

Install via composer

  After the first release it'll be much easier, but for now you'll need to add the package to your composer.json   "repositories": [         {             "type": "vcs",             "url": "https://github.com/cakephp/queue.git"         }     ]   Then do composer require cakephp/queue -W   And install some transport as stated in the official documentation https://book.cakephp.org/queue/1/en/index.html#installation composer require enqueue/redis:^0.9 composer require predis/predis:^1   Ensure your redis server is up and running, you can check the commands sent to your local redis server using redis-cli monitor   Now we are ready to configure the queue, we'll create 1 default queue adding this to the config/app.php file       'Queue' => [         'default' => [             'url' => 'redis:',         ],     ],   Add a Job using `bin/cake bake job Example` and add some code to the execute method       public function execute(Message $message): string     {         $data = $message->getArgument('data');           // do some long operation with data         Debugger::log($data);         sleep(2);           return Processor::ACK;     }   I've added a command utility to enqueue a test message bin/cake bake command addJob       public function execute(Arguments $args, ConsoleIo $io)     {         $callable = [ExampleJob::class, 'execute'];         $arguments = ['id' => 1, 'data' => ['some' => 'data']];           QueueManager::push($callable, $arguments);     }   And finally we can start our worker using bin/cake worker to pull jobs from Redis and process them using the ExampleJob::execute method   Here's all the example code created: https://github.com/cakephp/cakefest2020/tree/feature/cakephp-queue - for your reference.   Please note the plugin is still a work in progress and there is no stable release as of now.  It's looking great so far and we plan to include it in our next projects!  

Best CakePHP Plugins

Members of our team had the privilege of helping with CakeFest 2020 this year. One added virtual feature was the giveaways from CakePHP, these were done in the form of fastest-to-answer, trivia, or participation (random draw).  One of the giveaway games was to share your favorite CakePHP plugin but like, how do we only pick one, right? Anyway… There was a lot of participation in this giveaway! A few people even named our CakeDC Users plugin as their favorite *cue blushing face*. But in all seriousness, I thought it would be a good idea to share with you some of the plugins that were named most useful/helpful by CakeFest attendees this year….   Like I mentioned, the CakeDC users Plugin: https://github.com/CakeDC/users Queue Plugin: https://github.com/dereuromark/cakephp-queue Bake: https://github.com/cakephp/bake DataTables: https://github.com/fheider/cakephp-datatables CakePHP-tools: https://github.com/dereuromark/cakephp-tools Authentication: https://github.com/cakephp/authentication CakePHP-image: https://github.com/josbeir/cakephp-image Fixturize: https://github.com/lorenzo/cakephp-fixturize CakePHP File-Storage: https://github.com/burzum/cakephp-file-storage Crud: https://github.com/FriendsOfCake/crud IDE Helper: https://github.com/dereuromark/cakephp-ide-helper Asset-Compress: https://github.com/markstory/asset_compress CakePHP Debug Kit: https://github.com/cakephp/debug_kit Plum-Search: https://github.com/skie/plum_search CakePHP API: https://github.com/cakedc/cakephp-api/ Bootstrap UI: https://github.com/friendsofcake/bootstrap-ui Trash: https://github.com/usemuffin/trash   You can check out the full list of CakePHP Plugins at Plugins.CakePHP.org.  Have you been utilizing these tools? If not, it may be a good idea to start… while each of these serve their own purpose, using all of them can make your baking process a lot easier.    Perhaps your favorite didn’t make this list? Tell us about it… email HERE. Or, tweet us @CakeDC, @CakePHPThanks for baking!  

CakeFest 2020 recap

Taking a deep breath….. We have made it through another successful CakeFest event.    We didn’t know exactly what to expect with a fully virtual event, as it opens the door for a list of things that can (and most likely will) go wrong. Would the speakers show up? Would the internet connections keep things from running smoothly? Would attendees enjoy the information?   The answer to all of those questions is yes.    The lineup this year was amazing, and we had speakers from 6 different countries! With the ever changing way of life, our team wanted to have a diverse group of speakers, with some talking about some pretty serious subjects - like Dr. Jennifer Akullian and the mental health issues faced in the tech world. Jen allowed for questions and how-to-handle scenarios, and worked through some tough issues with attendees. Workshops from Mark Story, Jorge Gonzalez, Mark Scherer and Jose Lorenzo provided incomparable information while building projects in real time. All of the talks provided useful information that we hope all attendees will take with them as they bake in the future.    Now, does all of this bragging mean we didn’t have any issues? No. As I said in our opening, I think our group is pretty awesome and perfect, but the fact of the matter is, no one is. When bringing people together from all over the world, it is hard to test and check every connection multiple times. We had our fair share of internet lag, connection problems and audio issues. You know what we did? We worked together, fixed it, switched around the schedule and made it happen.   Virtual CakeFest 2020 was a great success, and exceeded our expectations. We were able to gather bakers from all over the world, in real time, and host a live event! I couldn’t believe how interactive the audience was, and everyone is still baking together in our #cakefest chat channel. I hope everyone is as impressed with the turn out as our team is. I know what you’re thinking… when will the recordings be released. We are working on uploading, editing and releasing the videos ASAP. While we tried to find the best universal timezone, we understand that other obligations kept some from attending, and we want to share these videos with you quickly, so know that we are working on it.    To our attendees: THANK YOU. Thank you for joining, supporting our framework and keeping CakePHP alive.   

I would like to thank all of our speakers:

  Remy Bertot  Junichi Okuyama Mark Story Jorge Gonzalez Jose Lorenzo Mark Scherer Jose Gonzalez Cal Evans Ed Barnard Jennifer Akullian Mariano Iglesias Chris Nizzardini Juan Pablo Ramirez
 

A HUGE THANK YOU TO OUR SPONSORS:

   Cake Development Corporation
  Passbolt 
  Marks Software
  RingCentral  


  Here’s to planning next year’s event to be even bigger and better!  

We Bake with CakePHP