In this post we are going to add a ‘users’ table to our MySQL schema ‘aa01′ and create a data model, a controller and some views.

Currently, if we load the URL http://localhost/aa01/index.php a Welcome page is displayed and the messages are mainly green, signifying all is well with our ‘aa01′ project. Now, if we type http://localhost/aa01/index.php/users or http://localhost/aa01/index.php/login, all hell breaks loose, the messages turn red, signifying not so well. Read messages carefully as they show a lot of info.

Users table

Let’s add the users table. Get into MySQL and run the following script. The minimum fields we need are id, username and password.

DROP TABLE IF EXISTS `aa01`.`users`;
CREATE TABLE  `aa01`.`users` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `username` varchar(45) NOT NULL,
  `firstname` varchar(45) default NULL,
  `lastname` varchar(45) default NULL,
  `active` tinyint(1) NOT NULL default '0',
  `email` varchar(100) default NULL,
  `password` varchar(40) default NULL,
  `randomsalt` varchar(40) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

While you’re in MySQL, add a couple of users like Joe, password ‘joe08′ and Jane with a password of ‘jane08′ just for testing.

Bake Model

Back to our staple comand line. Run cake bake -app aa01 again. A console command line shows asking what next.

Select ‘M’ for model, ‘1′ for the User model. Enter validation ‘alphanumeric’ for username and password. Skip model associations and press OK. The file \aa01\models\user.php will be created.

Note that the Bake console times out after 300 seconds, so if you take too long, you have to start again. Also action any requests for test file generation, so in the future you might test your project.

Bake Controller

Back to our staple comand line. Run cake bake -app aa01 again. A console command line shows asking what next.

Select ‘C’ for controller, ‘1′ for the Users model. Select ‘Interactively’, skip ‘Scaffolding’, include basic class methods. Skip admin routing, other helpers, components. Yes to using Sessions and press OK. The file \aa01\controllers\users_controller.php will be created.

Bake Views

Last in this baking series is to bake the simple views Index, Add, Delete and View. Back to the trusty bake command.

Select ‘V’ for Views, ‘1′ for Users model, Interactively, Yes to scaffolded basic views, No to admin routing, OK to create.

Some local tests

Try the URLs below;

http://localhost/aa01/index.php - Shows Welcome page

http://localhost/aa01/index.php/users – Lists users

http://localhost/aa01/index.php/users/add- Add a user

http://localhost/aa01/index.php/users/delete – fails to delete, lists users

http://localhost/aa01/index.php/users/list – fails

http://localhost/aa01/index.php/users/edit – fails to edit, lists users

http://localhost/aa01/index.php/users/view – fails to view, lists users

http://localhost/aa01/index.php/users/login – fails

http://localhost/aa01/index.php/users/logout – fails

http://localhost/aa01/index.php/users/register – fails

Almost finished

Now we have users loaded in the database, a basic working front end to our project (except login / logout / register) where we can add / delete / edit / list users. Go on, try adding, editing and deleting some users. Try silly things like submitting the add form with no username, watch for error messages.

The whole CakePHP process was simple after all, wasn’t it?
Next post is login / logout /register.

Recapping what’s been done so far;

  • Downloaded latest CakePHP v1.2.0.6311
  • Unzipped into folder as \htdocs\cake12
  • Baked project files into into my project folder \htdocs\aa01
  • Removed all .htaccess files

When the basic files were baked at the command prompt (see last post) , a number of things were actioned inside your project files. These are

  • Created a Welcome page
  • Created a new hash key
  • Altered the path to show where the core Cake files reside

Connecting to the database

Get into MySQL create a user with Select, Insert, Delete, Read, Create and Drop rights. Create a schema called ‘aa01′, matching the project name. Give the user rights to the newly created schema. I use a user called ‘fred’, password of ’shhh’ for all local projects whilst testing – makes it real easy.
Next, the project needs to link to the MySQL database, so what we do is run the bake project comand line again. Exactly the same command string as previously. On the second pass, the console looks for the database. Enter the schema name and the user name and password. Cake copies the file \aa01\config\database.php.default, loads your newly entered details and saves it as \aa01\config\database.php.

Opening the project

At this stage we should be able to open the Cake application and see whether it all works. The URL to use points at my separate project folder \htdocs\aa01 as below
http://localhost/aa01/index.php

When I try this URL, the Welcome screen from within the depths of the project at \aa01\views\pages\home.ctp is generated and it displays a series of messages, some of which might need slight fixups. Below are notes on each of these possible issues, noting that none or some may require a fixup in your project.

Issue 1 – Cake reports it is unable to locate the core files
The project file detailing where all the folders and files are located is \aa01\webroot\index.php. The first bake pass modified this file and loaded the path to the core Cake build files at \htdocs\cake12 into a variable called CAKE_CORE_INCLUDE_PATH. There are two other variables that I manually modify in this file – they are ROOT and APP_DIR. An excerpt from the modified index.php is below, starting at Line 35.

/**
 * These defines should only be edited if you have cake installed in
 * a directory layout other than the way it is distributed.
 * Each define has a commented line of code that explains what you would change.
 */
if (!defined('ROOT')) {
	//define('ROOT', 'FULL PATH TO DIRECTORY
            WHERE APP DIRECTORY IS LOCATED.
            DO NOT ADD A TRAILING DIRECTORY SEPARATOR');
	//You should also use the DS define to separate your directories
	//define('ROOT', dirname(dirname(dirname(__FILE__))));
	define('ROOT', 'c:\apache224\htdocs');
}
if (!defined('APP_DIR')) {
	//define('APP_DIR', 'DIRECTORY NAME OF APPLICATION');
	//define('APP_DIR', basename(dirname(dirname(__FILE__))));
	define('APP_DIR', 'aa01');
}
/**
 * This only needs to be changed if the cake installed libs are located
 * outside of the distributed directory structure.
 */
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
	//define ('CAKE_CORE_INCLUDE_PATH', 'FULL PATH TO DIRECTORY
                WHERE CAKE CORE IS INSTALLED.
                DO NOT ADD A TRAILING DIRECTORY SEPARATOR');
	//You should also use the DS define to separate your directories
	//define('CAKE_CORE_INCLUDE_PATH', ROOT);
	define('CAKE_CORE_INCLUDE_PATH', 'c:\apache224\htdocs\cake12');
}

On completion of the above changes/additions, reload the URL and see that the various messages re the lack of the core files have gone.

Issue 2 – A message re Security.salt shows as below.

Notice (1024): Please change the value of 'Security.salt'
in aa01/config/core.php to a salt value specific to your application
[CORE\cake\libs\debugger.php, line 535]

The security salt is used for generating hashes, particularly for password security. The Cake build has a default salt which should be changed otherwise there is the potential that another site with the same build and thus the same default salt could be well on the way to crack your passwords. Note that the first Cake bake pass should have modified this salt, but you can manually change it. Sometimes I manually generate a project salt based on the project name and build version so that I can check it during subsequent processing.
Change one or more characters of the salt or generate yourself a completely new salt. Use something like echo sha1(‘my own security salt string’) and copy the 40 character hashed string. The security.salt is stored in \htdocs\aa01\config\core.php at around line 153.

Once you’ve done that, reload the URL and see that the message re the salt has gone.

Issue 3 – Screen is a plain vanilla webpage with browser default colours of say black text and a few coloured hyperlinks. Got a fix for that too – the .htaccess files I removed apparently cause that because Cake can no longer find its CSS file at \htdocs\aa01\app\webroot\css. The message is below from around line 48 of \htdocs\aa01\congfig\core.php

/**
 * To configure CakePHP *not* to use mod_rewrite and to
 * use CakePHP pretty URLs, remove these .htaccess
 * files:
 *
 * /.htaccess
 * /app/.htaccess
 * /app/webroot/.htaccess
 *
 * And uncomment the App.baseUrl below:
 */
//Configure::write('App.baseUrl', env('SCRIPT_NAME'));

What we do here is uncomment the line at the bottom, reload the URL. All should now be in glorious colour. By uncommenting line 59, Cake now has a base URL for the application, thus can find and access the CSS file, dredging up a few garish colours. Green is an OK message, yellow can be ignored and red requires fixing.

Issue 4 – There is a message onscreen about being unable to find a configuration file called database.php. Message as below;

 Your database configuration file is NOT present.

Copy \htdocs\aa01\config\database.php.default to database.php. Modify this file (database.php) filling it with the detail needed to connect to the database, in our case MySQL. The second Cake pass should have done this (and Issue 5) operation already. Reload the URL and Issue 5 now appears.

Issue 5 – Cake cannot connect to the database. The database configuration file renamed at Issue 4 contains two arrays detailing how to connect to a specific database. The message displayed is below, having tried to connect and login to a MySQL database using the default array details. Note that the referenced code lines where the errors occur have nothing to do with what has to be modified to fix the issue. The joys of debugging.

Your database configuration file is present.

Warning (2): mysql_connect() [function.mysql-connect]:
Access denied for user 'user'@'localhost' (using password: YES)
[CORE\cake\libs\model\datasources\dbo\dbo_mysql.php, line 100]

Warning (2): mysql_select_db():
supplied argument is not a valid MySQL-Link resource
[CORE\cake\libs\model\datasources\dbo\dbo_mysql.php, line 105]

Cake is NOT able to connect to the database.

Set the details to suit your situation in the database configuration file at \htdocs\aa01\config\database.php.

For my local development MySQL database, in all projects, I use a standard user of ‘fred’, password of ’shhh’ and the database schema name matches the project name – in this case, a database schema name of ‘aa01′. Note that this Joe Public user ‘fred’ can only Select, Insert, Update and Delete within the MySQL database schema. No point in giving him elevated (more risk) rights he should never need to use, although initially I quite often add Create and Drop rights whilst I am sorting tables out. Create and Drop usually are removed before production.
Reload the URL and see that the screen report states that the database configuration file is present.

Issue 6 – Caching is turned on and using the File Engine.

Now I will readily admit that here I do not fully understand the implications, but I turn off all caching. When developing, I want every URL reload to serve up a new page loaded from the server, complete with any recent modifications I might have made. In a production server, caching might be good for overall speed, as some web pages may be stored locally and not have to be reloaded across the wire, be it via a network or the Internet.

To kill caching, back into \htdocs\aa01\app\config\core.php at line 75 and uncomment the line ‘Configure::write(‘Cache.disable’, true)’. Reload URL and see the message changes.

Summary

Note I have only addressed issues relating to my project in \htdocs\aa01. Similar issues still exist in the application (project) folder under the main build at \htdocs\cake12\app. I leave these alone, so it remains a clean master that could be used for a new project although I suspect when using Bake at the command line, these files are not used at all.
I have now

  • Loaded the latest build of CakePHP, with the project in a separate folder.
  • Told the project where specific Cake files are
  • Set our own salt for hashing
  • Turned off caching
  • Connected to a MySQL database

Next I am off hopefully to create a few views.

The start to *baking is to download the latest build of the platform. The one I’m using today is 1.2.0.6311 and it is downloaded from the downloads page on the CakePHP website. The file name I grabbed is cake_1.2.0.6311-beta.zip

As my platform is Windows XP, I have a My Documents folder which I refer to as MyDocs, which if not managed with a few sub-folders it can be a dumping ground, where it is hard to find anything. All my code downloads go into MyDocs under a folder called Code. There is a sub-folder called Cake, into which I dump the zipped files of the latest version. That way, when I back up things on the laptop, I might just grab the whole MyDocs folder, or just the Code folder, and everything in it.

Looks a bit like this:

 MyDocs
   ...
   Code
     ...
     ASP
     Cake
       ...
       cake_1.2.0.6311-beta.zip
       ...
     C#
     HTML
     PHP
     ...
   ...

When I open the zip file I am going to be asked where to extract the files to. I am using the free Apache webserver on my laptop, it lives at c:\apache224, so the structure looks like so:

 /
   ...
   Apache224 - this is the folder that contains
               my local Apache webserver
               for development and testing
               (version 224 by the looks of it)
     bin
     cgi-bin
     conf
     error
     htdocs  - this is the folder http://localhost lists
               when entered into a browser
               and also the folder I grab for backups
               of all my web work
       ...
       aa01 -  my various web projects below here
       ...
       cake12
       ...
       project01
       project53
       projectxyz
       ...
       phpinfo.php
       ...
     icons
     logs
     manual
     modules
   ...

Where I put the files is under the htdocs folders in a folder called \cake12. In Apache I have turned off the default auto open feature of index.php so I can see a listing of all my web projects when I type http://localhost into the browser address bar. This is my development machine, not a live public web server, so I want to see all my projects listed.

Some might disagree how I structure my folders. I like it this way, projects are totally separate from the \cake12 folder because when I test publish a project to the live web site, I only want to upload changes from the project folder. When developing and testing, the project files get changed often.

The core cake12 files only get loaded to the live site by me when a new build is released by CakePHP and I actually download it. The core files are in a different folder under htdocs, on both the local and the live websites, so that the files can be easily changed in their respective, but separate, folders. Each site closely mirrors the other – easier to follow – the only thing that changes is the domain name. Either locally I enter say http://localhost/index.php or on the live site I use http://mydomain.com/index.php.

The folder I am going to use for my project is \aa01. It is named with a leading ‘aa’ to present at the top of the list. This folder will be created automatically during the bake project process in the next post.
Note that I also have the file phpinfo.php in the root of my local website – there have been a fair few number of times I have had to open this file locally to check some info about my webserver settings. Do NOT put this file on the live website, it might give a hacker too much info.Keeping it simple initially takes a little thought about the folder structure and it seems to work effectively in practice.

*Baking – writing code / developing an application to run on the CakePHP platform

A slight mistake in the way I was going about things.

Have possibly found a better way to do things.  Have withdrawn 3x posts, revising them and will re-release them when I am convinced the new way works better.

Watch this space.

The light at the end of the tunnel is sometimes said to be the headlamp of an oncoming train.

I have managed to get managed to get various basics working like the MySQL database, an Apache webserver on my laptop and a working web page published on a hosting website to test my web efforts live. Not on an unsuspecting public though.

I use the laptop to develop my code, test it on the local Apache webserver and eventually load it to the live website, publishing the pages a few folders below the public face of the root page so I know where it is for testing, but where Joe Public hopefully doesn’t know they exist. A live website really tests whether you’ve got your code right – something might work locally because you might have buggered around with default settings , but you can guarantee a live site, with a background database will show up any coding errors.

The live site I use is www.iserve.co.nz which costs me NZD$20 a month and has a great interface. Support Kiwi made! There are any number of sites, I just picked one after Googling ‘free hosting nz’. Some options were did I want a PHP / MySQL interface or an ASP / SQL . PHP / MySQL was the option I wanted, both are free downloads for me to use on my laptop and I also wanted to learn PHP.

All have been part of the learning curve, keeping my brain active instead of mindless surfing some of the dross on the Net, but sometimes I definitely wonder about that bright light…

Welcome. This is the beginning of my written journey through CakePHP.

I have been impressed with CakePHP so far testing various things, but as with any language there is sometimes an over vertical learning curve. What I would like to do with these notes, is to journal the steps I take getting things working and the underlying ideas that go toward some areas.

I am certainly no expert, but have written many programs in many diverse languages mainly on a hobby basis. I do understand most programming concepts and am interested in using CakePHP as the core platform to explore interfacing a database based web application.

You, as a reader of this blog, are most welcome to add your tuppence worth. I have no problem using other baker’s code and value your input and questions. As a one finger keyboard basher coding with speed is not an option and my vintage deems that things may happen a little slower.

The name of this blog? A Pavlova is a sugar and egg meringue type cake, like me, slightly crusty on the outside, but light and fluffy inside. No, after being taken with Lemoncake’s bakery on CakePHP, I thought a cake that has caused much controversy between Ockers and Kiwis might be in order since I live in NZ.