Using validates() in cakePHP 1.2

December 4th, 2008

Today I was dealing with a nasty problem. I was trying to validate form data without saving it, which was supposed to work like this:


if ($this->Location->validates($this->data)) {}

The only problem was… it didn’t work! It took me some time until I figured out that the Parameter usage of validated() is deprecated: Thanks to cakebaker for his blog entry!

So if you are trying to achieve the functionality from above you should use this code instead:


if ($this->Location->create($this->data) && $this->Location->validates()) {}

cakePHP

Using Breadcrumbs with cakePHP

November 15th, 2008
Generating neat looking breadcrumbs (or breadcrumb trails) with cakePHP is almost too easy to write an extra article for it… but I’ll do it anyway. There are actually only two things that have to be done: Add the following line of code where you want your breadcrumbs to appear (that is the exact place in your design template):
<?php echo $html->getCrumbs(' > ','Home'); ?>

The first parameter of getCrumbs is the placeholder between two trail entries, which can be freely chosen. You can also replace “Home” with anything you like - this is going to be the first element of your breadcrumbs. And then second, add the specific bread crumbs to each view using this type of code:

<?php $html->addCrumb('Something', '/controller'); ?>
<?php $html->addCrumb('Something else', '/controller/method'); ?>

That’s it! You can add as many breadcrumbs to a view as you like - you also don’t have to worry about the location where you add the addCrumb call as it doesn’t matter. It just has to be somewhere in your view file. The navigation entries don’t have to belong to the same controller, so you can even combine different controllers and methods. There is only really one thing to notice: on your homepage where you usually only have the getCrumbs method called and no addCrumb call, there will be no breadcrumb trail shown! So don’t expect just a single “Home” or something to appear on the mainpage. Only “Home > First Entry” will be shown with additional crumbs added to your trail. If you want to have “Home” on your mainpage you can add an empty breadcrumb which will return “Home >”. I don’t think this is particularly nice, but have no better solution to offer at the moment. If you know a more elegant way of just displaying “Home” please let us know by commenting this entry!

cakePHP ,

Getting a Design - Using Joomla Templates for cakePHP

November 14th, 2008

Design is probably not an area of particular strength of cakePHP. And it’s not of me either… Designing a webpage from scratch requires a lot of work & time and is not something I particularly enjoy. Unfortunately there are almost no design templates available for cake (yet?). This might be a fruitful new project: creating a cakePHP template respository! On the other hand there are a lot of Joomla templates that can be freely used. Marco wrote a nice little tutorial on how to adopt a Joomla template to work with cakePHP.

So I decided to give this approch a try and grabbed a free template from Joomlahacks. As outlined in the tutorial mentioned above getting such a template to work with cakePHP requires the following steps:

  1. Copying CSS and images and getting the paths of the images right
  2. Modifying the index.php of the Joomla template to be used as our default.ctp

The first step is quite simple and shouldn’t be a problem. The second is not as straightforward though, so let me give you some hints.

  • Rename the index.php to default.ctp and see what happens.
  • Replace the entire <head> … </head> part with the heading from the official default.ctp. Most Joomla templates use javascript for changing fontsize dynamically on the webpage. I find this to be useless anyway so not having this JS available is not a problem for me. If the design relies on some other scripts you will have to include those scripts using standard cakePHP convention such as:
<head>
    <?php echo $javascript->link('script.js'); ?>
</head>
  • Work your way through each error message and try to fix the problems line by line.
  • Very important: Replace mosMainBody(); with the following code:

<?php $session->flash(); ?>
<?php echo $content_for_layout; ?>
  • Keep the original template open and try to get your template as close to the original as possible while removing errors.
  • If your Joomla template uses additional php scripts to generate a dynamic menu you can delete all this stuff as cakePHP is not using this anyway. You should instead keep the CSS for the dynamic menu and use a cakePHP approach of doing this. I’ll write an article on this later on.
  • Replace <?php mosPathWay(); ?> with the cakePHP implementation of breadcrumbs as described in my post here.
  • You most likely will find some mosCountModules(”) entries in the Joomla template. Those are being used to determine whether to show Joomla elements (such as a login box) or not. You can delete all those function calls, because there is nothing comparable with cakePHP (that is, unless you program it of course). It just depends on your design needs and wants whether you will have to use the provided element layouts with your new modified template or not.

This approach will allow you to get a simple design for your new project rapidly. It will not give you the full blown design that you might want to have eventually but takes you a whole leap forward in getting there. To give you an idea, of what your cakePHP project could look like at this stage (including a simple dynamic CSS list based menu) have a look at this example:

I hope this helped you with your approach of getting a decent looking cake layout up and running as efficient as possible. If you have any questions on this topic please comment this post and I’ll try to help you out!

cakePHP , ,

cakePHP: Baking the Controllers & Views

November 13th, 2008

After baking the models the next step is to bake the controllers.

This is very similiar you just chose C at the main menu and then go through the questions asked. You should not choose to build your controller interactively because then some basic functionality can be added automatically (Choose “Yes” on the next question). Adding admin routing is a good idea. If you are asked to enter a path for the admin routing stick with “admin” - the admin views will be named “admin_view.ctp” then. Admin views are handy because you can edit the regular methods and keep the functionality to easily edit anything in the database with the admin methods.

Baking the Controller

After you have baked all your controllers its time to bake the views. Again - same procedure:

Baking the Views

Now it’s time to have a look at your folders. In the controllers folder of your app you will finde all the controllers we just baked and in the views folder of your app you will find severl subfolders each filled with the views we just baked (and also the “admin_” views if you have chosen to create them). Believe it or not, your website has its full fundamental functionality already at this point! What follows now is just tweaking and designing… well, almost! ;-)

cakePHP , ,

cakePHP: Baking the Models

November 13th, 2008

After you have created your tables in your database you are ready to start Baking!

Bake is a command line tool that can be executed as a script. Open up terminal (Mac OS X) and go to your cake/console directory. From there you can start the command line tool for baking with

./cake bake

This works similiar if you are running Windows - for details on this check the docs. So after the script has launched you will see a screen similiar to this one:

Using Command Tool to Bake the Models

Choose M and the Baking for the models begins. You a first asked what kind of database configuration you would like to use. Just hit enter to use the default one. Then you can select what model you would like to bake. The list of possible models corresponds to the tables that you have created in the database:

Baking the models

After you have chosen the first table a series of questions will be asked. I would recommend not to use validation at this point as it can be done afterwards quite easy. But you should definitely bake the associations. Specific questions will be answered on your database model and you should select the right data associations (prerry straight forward):

Baking the models

After everything has been defined and looks good the model will be baked. You have to repeat those steps for every table that you want to access through a data model (most likely all of them). When you are done have a look at your app/models folder - in there you will find a PHP file for each model you have baked! Beautiful, isn’t it! The next step would be to bake the controllers.

cakePHP , , ,

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 , , ,

Building websites with cakePHP

November 13th, 2008

In the last article I described how to set up a smooth Apache, PHP & MySQL configuration using as much built in features of Mac OS X as possible and how to get cakePHP up and running.

The intention was to have a local cakePHP setup for developing a website. The website can later on be easily transfered to an external web hosting provider. The reason to do it this way is convenience! Because we’re running everything on our local machine we have full administrative rights AND the power to BAKE! Baking is one of the great tools of cakePHP that allows you to rapidly start with your website development. Building websites with cakePHP follows ideally this way:

  1. Design your database model on paper, in your head or using available software.
  2. Create the tables in the database using phpMyAdmin and following Cake convention (more on this later)
  3. Bake your Models
  4. Bake your Controllers
  5. Bake your Views - your website structure is ready at this point
  6. Add functionality, design etc.

So basically it all comes down to three points: your database design, the MVC-pattern & Baking. While I’m not a database expert myself it’s actually quite easy if you stick to one important rule: try not to have redundancy! I’ll show you later on what I mean by that when we design the database model for django.at (and the other sites that is). The MVC pattern is another important concept when developing with cakePHP (and most other frameworks as ZEND). It basically means that you try to split your application data (models), from the logic (controllers), from the layout (views). There is quite a good introduction available in The Cookbook that I would recommend to read.

And now onto Baking. You actually don’t have to use Baking to build a website with cakePHP as you can create everything manually as well. But Baking saves you tons and tons of time because what Baking does is to create your model, controller and view files automatically based on the database design documented through the tables you have created in your database.

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 , , , ,

Web Development Frameworks - cakePHP vs. ZEND

November 13th, 2008

If you want to create websites fast, and I mean really fast you sooner or later will look into using a framework. Frameworks are a great way to save time and nerves because they have a lot of often used functionality (e.g. user login etc.) already built in and also help you by providing a certain structure for your coding.

There are a lot of web development frameworks out there. One of the best known is probably Ruby on Rails. What I’ve seen this framework is really great, so if you happen to have no programming experience at all and want to learn a new programming language from scratch RoR is definitely going to be a good choice. I, for my part, have been coding PHP since 5 years or so and didn’t feel like learning a new language. But that’s not a big problem because there are several frameworks available for PHP as well. But which one to choose? I first had a look at the ZEND framework which is very popular. But I wasn’t really satisfied with it and kept looking. I finally found cakePHP and have never thought about switching to something else since then…

CakePHP

cakePHP is sometimes refered to as a PHP clone of RoR. I cannot comment on this really, because I have never used RoR myself but some features (e.g. Scaffolding) seem to be very similiar indeed. What is so great about the cakePHP framework is that you basically build your website based entirely on the framework. With ZEND you have far more freedom (e.g. with the database model) and that’s why it doesn’t support the development process as much. Another great thing about cakePHP is the community - although documentation is sometimes out of date, there are great tutorials and discussion groups to help you learning cakePHP and with problems that might occur.

cakePHP , , ,