Archive

Posts Tagged ‘MySQL’

Designing the database for a cakePHP website

November 13th, 2008

Ok, so the first and really really most important thing when working with cakePHP is to get the database structure right. Of course you can always change tables and fields afterwards but then you have to manually change the model and methods. So try to keep it as final as possible from the beginning.

What helps doing this is a graphical Database Design software. If you are running Windows check the MySQL Workbench out - it’s really nice. If you are running Mac OS like me you can hope that a version for us will be released some time soon…

Anyhow for the applications that I am going to built it will be sufficient to use a sheet of paper. Actually I came up with the DB design already. So first we want to have somer users that can register at the website, so lets create a simple table users that has the following fields (replace mydb with the name of your database):


CREATE  TABLE IF NOT EXISTS `mydb`.`users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(20) NULL ,
`password` VARCHAR(10) NULL ,
`email` VARCHAR(60) NULL ,
`created` DATETIME NULL ,
`modified` DATETIME NULL ,
PRIMARY KEY (`id`) )

There are a couple of things to notice here. First tables are always plural and lowercase in cakePHP. You have to follow this (and other) conventions closely so that cakePHP can communicate with the database automatically. Second there needs to be a field called id which works as the primary key. Field names are always lowercase and if you want to work with field names that consist of several words they have to look like this: usernameSomething. Do NOT use username_something! And lastly there are two fields called created and modified. You don’t have to worry about them because cake deals with them automatically - so just add them to all your tables and enjoy the magic of cake!

We also want to have some form of content for our websites. The content may vary according to the different websites we are going to make but basically those are just entries of websites, videopodcasts or advertisments. For this reason I have called the next table entries and it looks like this:

CREATE  TABLE IF NOT EXISTS `mydb`.`entries` (
`id` INT NOT NULL AUTO_INCREMENT ,
`user_id` INT NULL ,
`name` VARCHAR(255) NULL ,
`rating` DOUBLE NULL ,
`ratingCount` INT NULL ,
`url` VARCHAR(255) NULL ,
`picture` VARCHAR(45) NULL ,
`views` INT NULL ,
`created` DATETIME NULL ,
`modified` DATETIME NULL ,
PRIMARY KEY (`id`) )

Now comes a little bit of a tricky part: the relation between users and entries. One user can make several entries to the database but one entry can only have one corresponding user. This is called a hasMany association between entries and users. For this reason we have included the column user_id in the table entries.

Next we want to have tags so that we can categorize our entries. The tag table is really very simple and short:


CREATE  TABLE IF NOT EXISTS `mydb`.`tags` (
`id` INT NOT NULL AUTO_INCREMENT ,
`tag` VARCHAR(45) NULL ,
`created` DATETIME NULL ,
`modified` DATETIME NULL ,
PRIMARY KEY (`id`) )

At this point in time you might wonder. Where is the association between entries and tags? Good question - at the moment there is none! We will have to create a new table for this purpose. We have to do so because entries and tags have a HABTM association. This wonderful acronym stands for hasAndBelongsToMany - which means that a tag can have several entries and an entry can have several tags at the same time. By adding this table to the database cakePHP will be able to tell that we have this kind of relationship in mind. Be careful to closely follow convention when adding this table. It has to be named entries_tags and consists of the following fields:


CREATE  TABLE IF NOT EXISTS `mydb`.`entries_tags` (
`id` INT NOT NULL AUTO_INCREMENT ,
`entry_id` INT NULL ,
`tag_id` INT NULL ,
PRIMARY KEY (`id`) )

It is cakePHP convention to have the table with the higher alphabetical order second (practically tags_entries would work as well). Lastly we want our users to be able to comment on the varies entries. To make this happen we need a table comments:


CREATE  TABLE IF NOT EXISTS `mydb`.`comments` (
`id` INT NOT NULL AUTO_INCREMENT ,
`user_id` INT NULL ,
`entry_id` INT NULL ,
`text` TEXT NULL ,
`created` DATETIME NULL ,
`modified` DATETIME NULL ,
PRIMARY KEY (`id`) )

This table has to associations - one with users and one with entries. So each comment belongs to one user and to one entry. When everything is set up we are ready to proceed with Baking the Models!

cakePHP , , ,

Setting up cakePHP on Mac OS X

November 13th, 2008

It’s actually quite simple to set up cakePHP with Mac OS X because most of the functionality you need comes already shipped with your system. Therefore I’m showing here how to use as much of the built in software such as Apache as possible to get cake up and running. Of course, alternatively you could use a local development environment such as MAMP. But why bother with an additional piece of software when Apache & PHP are already integrated in your Mac? And also you have greater flexibility when it comes to using virtual hosts (unless you buy the Pro version of MAMP). I recommend to give it a try - it’s not that hard: just follow these steps:

Prepare your Mac with Apache, PHP and MySQL

  1. Activate your built-in apache webserver by going to the system settings -> Sharing -> Web-Sharing and checking the box to enable it
  2. In the web-sharing options it should now give you an URL of the website of your computer and your personal website. Try accessing both by clicking on the links. The first link should give you an “Apache it works screen”. The second link should show you an intro page in Mac design.
  3. If you get the error message “Forbidden” on the second like (I did…) follow these steps to fix this. One note: Open finder and use the “Go to” feature to get to the directory /etc/apache2/users/
  4. Now our webserver is running and we can display static html webpages. The path where your website is stored is: /Users/yourusername/Sites/
  5. In order to run cakePHP we need to activate PHP. This guide basically gives you all the info you need to succeed with this task. In this article you will also find useful information on working with virtual hosting (ie having multiple websites on your computer).
  6. Next we want to install MySQL. This is described in the article above as well, but since this is already about a year old life is actually much easier. Just download the latest MySQL Package and start the installer. Then start the MySQL server from the command line or control panel and give your root user a new password.
  7. What is always nice to have is phpMyAdmin - this is a great web interface to control your MySQL database. Download it and put it in a directory of your Websites folder. From there you can access it using the URL: http://localhost/~yourusername/thedirectory/

Installing cakePHP

  1. Download the latest version of cakePHP (use the .dmg File).
  2. Mount the file, copy its content to a directory in your Websites folder and unmount the file again.
  3. If you point your browser to this directory (as shown above) you should be able to see the first output of cakePHP - and quite some errors. So let’s fix those:
Warning (512): /.../app/tmp/cache/ is not writable

To fix this you have to make the cache directory writeable. In fact you should make the whole tmp directory writeable. Go to your app/tmp directory and change the read/write permissions for “everyone” to read & write (do this for all subfolders as well using the option just below the permissions field).

Notice (1024): Please change the value of 'Security.salt'...

For this just go to your app/config/core.php file and change the value of the string where it says:


Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');

and change the value of the string to something else. The length doesn’t matter, but I recommend to keep it this length and also in this form (random).

Your database configuration file is NOT present.

To configure the database rename the file database.php.default to database.php and set the parameters in it according to your setup. E.g. you can add a new user with a new database using phpMyAdmin and set those values in the database.php

Now all error messages should be gone. But there is still one thing to do - the design is not working as it is plain text only and the CSS does not seem to load. To fix this we need to set the DocumentRoot of Apache to the /app/webroot directory. To do this we have to define a virtual host and the corresponding DocumentRoot. How to do this is explained here again. Just extend the path of the virtual server with /app/webroot in your username.conf as shown in the guide and things should work. Don’t forget to restart your Apache (by deactivating and activating the Web-Sharing in your control panel) for the changes to take effect!

And then… there is actually one more last thing. Apache on Mac OS X is by default configured not to work with .htaccess files! That’s something we have to change in order to get cakePHP to work. And because we have a virtual server environment set up we can do this in the username.conf file again. Add the following bold lines of code for every virtual host definition:

<virtualhost *:80>
    DocumentRoot /Users/yourusername/Sites/pathttocake/app/webroot
    ServerName pathtocake
    <Directory "/Users/yourusername/Sites/pathtocake">
    Options Indexes FollowSymLinks
    AllowOverride All
    </Directory>
</virtualhost>

Now everything should be set up! If anything was unclear please comment on this post - I’ll try to answer your questions and/or improve the describtions!

cakePHP , , , ,