CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Quick start with Migrations plugin

In a previous post I gave an overview of the CakePHP Migrations plugin, what it does and why you should use it in your applications. This article will explain how to use it in a practical way. We are going to bake a simple blog application recipe application and see how migrations are integrated in the development process.

Since we recently moved all our open source projects on http://cakedc.github.com/, this sample application source code is also available there: Sample Migrations Application - Github (it is a CakePHP 1.3 application). Ready?

Bake a new application and add the migrations plugin

First of all, we need to bake a new CakePHP application. Easy enough to do using cake bake, then configure your database (an empty database is sufficient for now) and check that the home page is all green! If you have not set up your environment to use the CakePHP command line yet, take some time to do so... it worth it!

Adding the migrations plugin might also be a straightforward task. You can either download the archive containing the plugin code and unzip it in the "/plugins/migrations" folder of your application, or  add it as a git submodule with the following command:

git submodule add git://github.com/CakeDC/Migrations.git plugins/migrations

Then check that it is correctly installed by executing the following command from your application root:

cake migration help

If you see a list of available commands you can move on next step.

Create initial tables and bake the MVC

We now need something to migrate! Let's create some tables in the database. The application will have Users who can publish Recipes, each one having several Ingredients (of course Ingredients can be used in many Recipes). Here is a SQL dump of this simple database schema:

CREATE TABLE `ingredients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `ingredients_recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ingredient_id` int(11) NOT NULL,
  `recipe_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `recipes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

As our goal here is not to focus on the application code itself, baked MVC from these tables might be sufficient... just run the command cake bake all for User, Recipe and Ingredient to bake'em all!

At this point we must have an application with an initial architecture ready to share. To start from here, one will just have to checkout the related commit... but don't you see a problem with this? How will he create the initial database? Maybe we could send him the SQL dump by email, or better commit it with the application! It is where the Migrations plugin comes in.

Generate the initial migration

"Be kind with your coworkers and include the database schema with your code... along with some sample data."

Let's use the migrations shell to generate an agnostic database schema containing our 4 tables, and an initial admin user account. To do so we just need to run the following command:

cake migration generate

After entering a name for the migration and selected the database dump option, we might have a new "/config/migrations" directory containing two files:

  • map.php representing the different migrations order,
  • name_of_the_migration.php a migration file containing all the necessary information to create your actual database. In the sample application it is named: "001_added_users_recipes_and_ingredients_tables.php". You might have noticed that we added a 001 prefix to the migration name to make it easier to see migrations order, it is a good practice.

We can now open the generated migration file (/config/migrations/001_added_users_recipes_and_ingredients_tables.php) and take a look at it. If you need more information and understand all available migration directives, you can read the plugin documentation.

For now we are just going to focus on the empty "after()" callback. This callback is triggered once the migration has been executed, and allow you to do whatever you want, given the direction of the migration: applied (up) or reverted (down). We are going to use this callback to create an initial admin User. Here is the code of the callback (as you are a CakePHP developer you might understand it quite easily):

function after($direction) {
	if ($direction === 'up') {
		if (!class_exists('Security')) {
			App::import('Core', 'Security');
		}

		$User = $this->generateModel('User');
		$user = array(
			'User' => array(
				'name' => 'admin',
				'password' => Security::hash('unsecurepassword', null, true)));
		$User->save($user);
	}
	return true;
}

Notice the use of the generateModel() method provided by the Migrations plugin. It is a shorthand allowing you to cleanly load a model in the callback to insert new data or update the existing. We could explain the reason of it more deeply but it is not the goal of this article, so just keep in mind that it is the best way to load a Model from callbacks!

Here we are! We can now share the application with anyone. After checked out the application, one will just have to run cake migration all to turn an empty database to a database containing all the needed tables, and an initial admin user to start using the application.

Categorize the recipes!

As the application evolves, we need to sort recipes by categories. This change involves two changes in the current database schema: a new categories table must be created, and a category_id field added to the recipes table.

Note: If you later want to use the migrations diff feature to generate a migration containing a diff between your previous database schema and the current one, you have to generate a Cake Schema of your database at this point. Simply run cake schema generate.

We can now update the recipes table and create a new categories table. Here is a simple SQL script:

CREATE TABLE `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;
ALTER TABLE `recipes` ADD `category_id` INT NOT NULL

Bake the MVC for categories and update recipes view pages to display the category so the application reflect these database changes. Before sharing these code changes, we need to generate a second migration describing the above SQL snippet in an agnostic way... and creating initial categories!

Nothing different than what we did previously: run cake migration generate, give a name to the migration, and choose between generating a diff from the schema.php file (if one was generated), generating a dump of the database (we will remove unnecessary instructions later) or generating an empty migration file. Once generated, it is always important to check the generated directives for the migration and fix them if needed. The migration must look like this:

var $migration = array(
	'up' => array(
		'create_table' => array(
			'categories' => array(
				'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
				'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100),
				'indexes' => array(
					'PRIMARY' => array('column' => 'id', 'unique' => 1),
				),
				'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM'),
			),
		),
		'create_field' => array(
			'recipes' => array(
				'category_id' => array('type' => 'integer', 'null' => false, 'default' => NULL)
			),
		),
	),
	'down' => array(
		'drop_table' => array(
			'categories'
		),
		'drop_field' => array(
			'recipes' => array(
				'category_id'
			),
		),
	),
);

If you understood what we did in the first migration callback to add an initial user you might be able to implement this one. We would like to add initial categories: Starters, Main Dish and Desserts.

For lazy people, the code is here:

function after($direction) {
	if ($direction === 'up') {
		$Category = $this->generateModel('Category');
		$categories = array(
			array('name' => 'Starters'),
			array('name' => 'Main Dish'),
			array('name' => 'Desserts'));
		$Category->saveAll($categories);
	}
	return true;
}

Here we are again! The changes are ready to commit, and the commit will contains both code and database changes. One could update the database after checking out this commit by running: cake migration all.

The end

I hope this very simple use case and the code we built will help you to start using Migrations. As you could see it is very simple to use and will make your life much more easier: you would not have to worry anymore about the state of your database schema.

The source code of this tutorial is available on Github. If you found any bug or have any suggestion about the Migrations plugin, please create a ticket on Github. Comment this article if you have any question, and do not hesitate to share it if you found it useful!

Latest articles

Why You Should NOT Upgrade Your CakePHP Project

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!  

We Bake with CakePHP