Wednesday, November 11, 2009

CakePHP - Classes & File Name Convention with Example

In this topic I'll tell you the CONVENTIONs you MUST follow for Cake to work properly making your coding life SIMPLE.
You may already know (if you are following this tutorial...) that to create a database driven application you need to create following files.
1. One file to define data model (data model file)
2. One file to define how database queries should be processed (controller file).
3. One or more files to present the query results.
While creating these files you need to follow CakePHP naming CONVENTIONs. This is very important for the whole framework to work properly.

Database Table & Field Name Convention:
1. Create your database.
2. Table name convention - lowercase, plural, multi-word tables to be separated by underscore.
    Example table name:  posts
2. Each table must have one PRIMARY KEY to be named as 'id' (NOT NULL Auto Increment).
3. Field name convention - lowercase, multi-word field to be separated by underscore
    Example field name: id, title, body, created, modified
4. Foreign Key (related_table_name)_id

Model Name Convention
1. Model class names are CamelCased and Singular. (Like: Post, MyClass etc.). This should be the database table name.
2. Model filenames are lowercase, multi-word class is to be separated by underscore. (Ex: post.php, my_class.php)
3. Model files are saved under 'app/models' folder.

Controller Name Convention
1. Controller class names are CamelCased, Plural, and MUST contain the word 'Controller'. (Ex: PostsController, MyClassesController etc.)
2. Controller file names are lowercase, multi-word to be separated by underscore, and must contain the word '_controller'. (Ex: posts_controller.php, my_classes_controller.php)
3. Controller files are saved under 'app/controllers' folder.

Views Name Convention
1.View files are stored in /app/views inside a folder named after the controller class name they correspond to. i.e., for PostsController the corresponding view files are to be saved under '/app/views/posts' folder.
2. View filenames are function_name.ctp and saved under above path. (The function name is the name of the function you have used in corresponding Controller file.) This is really simple, if you go through the example below.    

Example Database & Table
1. In my case I created a database 'caketest_db'. You can create any database of your choice. You need to use this database name in your 'app/config/database.php' file.
2. Now create a table - posts.

SQL:

CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);


Add some data


INSERT INTO posts (title,body,created)
    VALUES ('The first CakePHP Blog Post Title', 'This is the first CakePHP blog post body.', NOW());
INSERT INTO posts (title,body,created)
    VALUES ('Second Blog Post Title', 'Second blog post body.', NOW());
INSERT INTO posts (title,body,created)
    VALUES ('Third Blog Post Title', 'Third blog post body', NOW());


Now create a post model
1. Create a new file.
2. Copy paste the following code

<?php    class Post extends AppModel 
         {      var $name = 'Post';  }    
?>
3. Save the file as '/app/models/post.php'. 
 And you are done creating your first post model.


Now create a post controller
1. Create a new file.
2. Copy paste the following code


<?php  
class PostsController extends AppController { 
   var $name = 'Posts';    
function index() { 
  $this->set('posts', $this->Post->find('all')); 
}  
}  
?>
3. Save the file as posts_controller.php inside the /app/controllers directory



In this file we have created a controller class for Post model. We have also defined a function index() ('Cake calls functions as 'action'). 
This is the default function to be executed by Cake. 
This function tells cake to find all rows from posts table and save it in a variable 'posts' (Note, $this->Post->find('all') - this is same as 'SELECT * FROM posts' ).

Now Create Views
1. Create a new folder 'posts' under '/app/views' folder.
2. Now create a new file
3. Copy paste the following code in that file

<h1>Blog posts</h1>
  <table>
  <tr>
  <th>Id</th>
  <th>Title</th>
  <th>Created</th>
  </tr>
 <!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
  <tr>
  <td><?php echo $post['Post']['id']; ?></td>
  <td>
  <?php echo $html->link($post['Post']['title'], 
  "/posts/view/".$post['Post']['id']); ?>
  </td>
  <td><?php echo $post['Post']['created']; ?></td>
  </tr>
  <?php endforeach; ?>
</table>
(You can get a copy of this code here
4. Save the file as index.ctp under '/app/views/posts' folder.

And you are done.
Now to see your result:

Point your browser to:
http://caketest.local/posts

You can see all records from the post controller.
Here is the screenshot:


7 comments:

Unknown said...

what if, for example,
class ServerType extends AppModel {
var $name = 'Server Type';
}


is the var $name right?

Anonymous said...

Do not use SPACE between "Server Type", use ServerType instead. I think it should work as it has worked for ME....

Chris Wayne G. Comendador said...

Ei! mycakephp..

I've been finding ways how I could learn cakephp fast..

Thanks for making this one!

Siddhartha said...

Thanks Chris... It is a great pleasure to see that this blog has helped someone... :)

Dhariz web simiplied said...

can u explain controller has this line
$this->set('posts', $this->Post->find('all'));

how it calls tables name and
what is the use of $name
var $name = 'Posts';

Unknown said...

hi
how controller how it connect to db and view pages

$this->set('posts', $this->Post->find('all'));

in where to give table name?

Unknown said...

hi
in model and controller why assigning $name=Post?
and where it used? and
in view foreach ($posts as $post)
in coding where we assingn $posts