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

Simplicity is important - here’s why

When it comes to web design, simplicity is not valued enough. Simplicity is important - but why? Simplicity reduces navigation confusion, makes the website look more sophisticated and can help in increasing site conversions (sign ups, contacts). All too often, web designers tend to miss the point of simplicity and over do the amount of information given on a single page - the need to get everything across at once can seriously hinder how much a website visitor is able take in. Over complicated pages can lead to higher than average bounce rates or lower on-page conversions. We thought we’d share with you some top tips to simplify your website.

  • Keep things along the 80-20 rule
    • Use the Pareto principle which is that 80% of the effects come from 20% of the causes. This means taking away as much as you can from your design that will not lead to any type of conversion. Take things back to the bare essentials and make those work properly
  • Embrace few colors in your theme
    • Does a monochrome color scheme work for you? If not, try out as few colors as possible. Work towards a design that requires less effort for your website visitor to process. Fewer colors will also give your site a sleek, classic look
  • Keep copy short and sweet
    • Embrace compelling copy but keep things shorter and to the point. Make your point quickly and keep things easy-to-read by sticking to a few key points. Use shorter sentences, and keep paragraphs to a maximum of 3-4 sentences for easy reading.
  • Fix your navigation
    • Often many sites have over complicated and lengthy navigation options. Remember to include navigation to your list of things to simplify today. Keep important and key pages in your navigation bar. Remove excess clutter and keep all navigation menus visible. Other key things to keep in mind is the use of universal icons as well as ensuring a sitemap in your footer - these are all standard items that visitors look for.

How Much Does it Cost to Design a Site?

If you are in the market for a website or application, it can sometimes be daunting. Being unsure of where to start, which development firm to use or how much the whole process is going to cost you can be truly overwhelming. And then there are those horror stories of others, who selected a developer based solely on cost (the cheapest quote perhaps) and ended up majorly down the hole with their budgets, while owning a unfinished website. Whether you are in the market for a website application with a specific outline and goal, or have a rough idea of what you need your application to do, how do you go about finding the best selection for you? And then how do you know that whoever you select is going to deliver what you want and in the time frame that you need it? And then, not knowing how to code yourself, you can land up frustrated at not understanding the process - especially if your development team gives you the runaround. At CakeDC, we are committed to a transparent workflow - we've created our own git workflow (MIT license) and we've used it successfully with our clients for 3+ years and dozens of projects. We use it to accelerate growth and innovation providing the highest quality application development. What sets CakeDC apart from others is that our experts listen closely to your needs. Second, we formulate a roadmap of milestones based on your specifications. Third, we offer guidance while delivering the highest quality results in a fraction of other developer’s time, by doing things The Right Way™ So how much is it going to cost you? Well this is of course dependent on what you project scope includes, however, we will work with you in determining the best package to suit your requirements. You can check out all of our rates and packages here. Ready to get your project started? Reach out to our experts today to see how easy it can be to get your application up and running.

What your website users are trying to tell you

Every visitor to your website has a goal in mind - this may not be a conscious goal, but they are visiting your site for a reason. So listening to your users feedback is key to meeting their expectations! As a business owner, be sure to keep these in consideration and as a developer, be sure to pass these recommendations through to your clients. What are some things that users are trying to tell you and how do you find out? What and why is it Often people forget about the basics and fail to include what their product, service or business is. By excluding this vital information there will be users who will not know what the purpose of the page that they have stumbled upon is, but what to do next - and therefor bounce quickly off of your site. Where is your pricing information? If you are trying to sell something - a product or a service - be sure to include the price information as this is used by your visitor to determine their next action. Even if you are providing resources in return for their details, it is important to be clear. Where are those testimonials or reviews? Have others tried it People like to know that whatever they are investing money into is worth it - reviews or customer testimonials help to show your visitors what you can do. Be sure to add this information in a way that is easy for you visitors to find. Where can I sign up or contact you Another vital piece of information that many often forget is to let your visitors know how to signup and contact you. Perhaps you have chosen to hide your contact information due to spam bots or other issues faced, however, if you are in the business of recruiting clients, then be sure to have some form of contact information easily available to your visitors.
Not sure if you are missing anything? CakeDC, the experts behind CakePHP, offer a range of services including consulting, guiding you through the best practices with your CakePHP application.

We Bake with CakePHP