Wednesday, December 24, 2008

Next, we'll create a controller for our posts. The controller is where all the business logic for post interaction will happen. In a nutshell, it's the place where you play with the models and get post-related work done. We'll place this new controller in a file called posts_controller.php inside the /app/controllers directory. Here's what the basic controller should look like:
class PostsController extends AppController {

var $name = 'Posts';
}
?>
Now, lets add an action to our controller. Actions often represent a single function or interface in an application. For example, when users request www.example.com/posts/index (which is also the same as www.example.com/posts/), they might expect to see a listing of posts. The code for that action would look something like this:
class PostsController extends AppController {

var $name = 'Posts';

function index() {
$this->set('posts', $this->Post->find('all'));
}
}
?>

Let me explain the action a bit. By defining function index() in our PostsController, users can now access the logic there by requesting www.example.com/posts/index. Similarly, if we were to define a function called foobar(), users would be able to access that at www.example.com/posts/foobar.
You may be tempted to name your controllers and actions a certain way to obtain a certain URL. Resist that temptation. Follow CakePHP conventions (plural controller names, etc.) and create readable, understandable action names. You can map URLs to your code using "routes" covered later on.

The single instruction in the action uses set() to pass data from the controller to the view (which we'll create next). The line sets the view variable called 'posts' equal to the return value of the find('all') method of the Post model. Our Post model is automatically available at $this->Post because we've followed Cake's naming conventions.

To learn more about Cake's controllers, check out Chapter "Developing with CakePHP" section: "Controllers".

Create a Post Model

The Model class is the bread and butter of CakePHP applications. By creating a CakePHP model that will interact with our database, we'll have the foundation in place needed to do our view, add, edit, and delete operations later.

CakePHP's model class files go in /app/models, and the file we'll be creating will be saved to /app/models/post.php. The completed file should look like this:


class Post extends AppModel {
var $name = 'Post';
}

?>

Naming convention is very important in CakePHP. By naming our model
Post, CakePHP can automatically infer that this model will be used in

CakePHP will dynamically create a model object for you, if it cannot find a corresponding file in /app/models. This also means, that if you accidentally name your file wrong (i.e. Post.php or posts.php) CakePHP will not recognize any of your settings and will use the defaults instead.

The $name variable is always a good idea to add, and is used to overcome some class name oddness in PHP4.

For more on models, such as table prefixes, callbacks, and validation, check out the Models chapter of the Manual.



the PostsController, and will be tied to a database table called posts.

A Note on mod_rewrite

Occasionally a new user will run in to mod_rewrite issues, so I'll mention them marginally here. If the CakePHP welcome page looks a little funny (no images or css styles), it probably means mod_rewrite isn't functioning on your system. Here are some tips to help get you up and running:

  1. Make sure that an .htaccess override is allowed: in your httpd.conf, you should have a section that defines a section for each Directory on your server. Make sure the AllowOverride is set to All for the correct Directory. For security and performance reasons, do not set AllowOverride to All in . Instead, look for the block that refers to your actual website directory.

  2. Make sure you are editing the correct httpd.conf rather than a user- or site-specific httpd.conf.

  3. For some reason or another, you might have obtained a copy of CakePHP without the needed .htaccess files. This sometimes happens because some operating systems treat files that start with '.' as hidden, and don't copy them. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository.

  4. Make sure Apache is loading up mod_rewrite correctly! You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so or (for Apache 1.3) AddModule mod_rewrite.c in your httpd.conf.

If you don't want or can't get mod_rewrite (or some other compatible module) up and running on your server, you'll need to use Cake's built in pretty URLs. In /app/config/core.php, uncomment the line that looks like:

Configure::write('App.baseUrl', env('SCRIPT_NAME'));

Also remove these .htaccess files:

/.htaccess
/app/.htaccess
/app/webroot/.htaccess

This will make your URLs look like
www.example.com/index.php/controllername/actionname/param rather than
www.example.com/controllername/actionname/param.

Optional Configuration

There are two other items that can be configured. Most developers complete these laundry-list items, but they're not required for this tutorial. One is defining a custom string (or "salt") for use in security hashes. The second item is allowing CakePHP write access to its tmp folder.

The security salt is used for generating hashes. Change the default salt value by editing /app/config/core.php line 153. It doesn't much matter what the new value is, as long as its not easily guessed.

/**
* A random string used in security hashing methods.
*/
Configure::write('Security.salt', 'pl345e-P45s_7h3*S@l7!');
?>

The final task is to make the app/tmp directory web-writable. The best way to do this is to find out what user your webserver runs as () and change the ownership of the app/tmp directory to that user. The final command you run (in *nix) might look something like this.

$ chown -R www-data app/tmp

If for some reason CakePHP can't write to that directory, you'll be informed by a warning while not in production mode.

Onward and upward: let's tell Cake where our database is and how to connect to it. For many, this is the first and last time you configure anything.

A copy of CakePHP's database configuration file is found in /app/config/database.php.default. Make a copy of this file in the same directory, but name it database.php.

The config file should be pretty straightforward: just replace the values in the $default array with those that apply to your setup. A sample completed configuration array might look something like the following:

var $default = array(
'driver' => 'mysql',
'persistent' => 'false',
'host' => 'localhost',
'port' => '',
'login' => 'cakeBlog',
'password' => 'c4k3-rUl3Z',
'database' => 'cake_blog_tutorial',
'schema' => '',
'prefix' => '',
'encoding' => ''
);

Once you've saved your new database.php file, you should be able to open your browser and see the Cake welcome page. It should also tell you that your database connection file was found, and that Cake can successfully connect to the database.

Creating the Blog Database

Next, lets set up the underlying database for our blog. Right now, we'll just create a single table to store our posts. We'll also throw in a few posts right now to use for testing purposes. Execute the following SQL statements into your database:

/* First, create our posts table: */
CREATE TABLE posts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);

/* Then insert some posts for testing: */
INSERT INTO posts (title,body,created)
VALUES ('The title', 'This is the post body.', NOW());
INSERT INTO posts (title,body,created)
VALUES ('A title once again', 'And the post body follows.', NOW());
INSERT INTO posts (title,body,created)

The choices on table and column names are not arbitrary. If you follow Cake's database naming conventions, and Cake's class naming conventions (both outlined in "CakePHP Conventions"), you'll be able to take advantage of a lot of free functionality and avoid configuration. Cake is flexible enough to accomodate even the worst legacy database schema, but adhering to convention will save you time.

Check out "CakePHP Conventions" for more information, but suffice it to say that naming our table 'posts' automatically hooks it to our Post model, and having fields called 'modified' and 'created' will be automagically managed by Cake.


VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());

Getting Cake

First, let's get a copy of fresh Cake code.

To get a fresh download, visit the CakePHP project at Cakeforge: http://cakeforge.org/projects/cakephp/ and download the stable release. For this tutorial you need 1.2.x.x

You can also checkout/export a fresh copy of our trunk code at: https://svn.cakephp.org/repo/trunk/cake/1.2.x.x/

Regardless of how you downloaded it, place the code inside of your DocumentRoot. Once finished, your directory setup should look something like the following:

/path_to_document_root
/app
/cake
/docs
/vendors
.htaccess

Now might be a good time to learn a bit about how Cake's directory
structure works: check out Chapter "Basic Principles of CakePHP",
Section : CakePHP File Structure.
index.php

Blog

Welcome to Cake! You're probably checking out this tutorial because you want to learn more about how Cake works. It's our aim to increase productivity and make coding more enjoyable: we hope you'll see this as you dive into the code.

This tutorial will walk you through the creation of a simple blog application. We'll be getting and installing Cake, creating and configuring a database, and creating enough application logic to list, add, edit, and delete blog posts.

Here's what you'll need:

  1. A running web server. We're going to assume you're using Apache, though the instructions for using other servers should be very similar. We might have to play a little with the server configuration, but most folks can get Cake up and running without any configuration at all.
  2. A database server. We're going to be using mySQL in this tutorial. You'll need to know enough about SQL in order to create a database: Cake will be taking the reins from there.
  3. Basic PHP knowledge. The more object-oriented programming you've done, the better: but fear not if you're a procedural fan.
  4. Finally, you'll need a basic knowledge of the MVC programming pattern. A quick overview can be found in Chapter "Beginning With CakePHP", Section : Understanding Model-View-Controller. Don't worry: its only a half a page or so.

Let's get started!

Tuesday, June 17, 2008

Link to CakePHP website

you can download latest version from the CakePHP website.