Date: 2005-10-19
This is a PHP-based framework. Its author says the Cake PHP framework is designed from 37signals Ruby on Rails, a very recent ruby framework
Similar to Ruby on Rails, it encapsulates database connections, templates, and build links. The biggest feature is data manipulation, without the need to write how much code. Similar to Ruby on Rails, it produces a data table at least as long as a single line of code. Cake PHP Framework also has a big advantage is that it is a lightweight framework, although the first time it seems to feel very magical, but look at its code is very understood and nothing special, but its development and use of the way is really unique, practical, efficient. If it is a database-based PHP system, this is a good choice to consider.
Take a look at Cake Tutorial to see how quick and easy it is to build a WEB application with the Cake PHP framework. It describes how to quickly build a blog program example, a few minutes can be done.
More and more interesting in the discovery of PHP world, haha.
Load download
Download the latest cake package and unzip it to the document_root of your Web server (because this is the guide, I assume he can access it from the http://localhost/cake/). You can see the basic directory structure.
Create a database
Create a table to hold blog posts, and initialize some data. The following is the SQL statement:
CREATE TABLE Posts (
ID INT UNSIGNED auto_increment PRIMARY KEY,
Title VARCHAR (50),
Body TEXT,
Created DATETIME DEFAULT NULL,
Updated DATETIME DEFAULT NULL
);
INSERT into posts (title,body,created)
VALUES (' The title ', ' This was 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)
VALUES (' Title strikes ', ' this is really exciting! Not. ', now ());
Note The table name is a plural form, which is the default form for all tables used by cake. Also, the ID, created, updated fields have special meanings, and you'll find them in a moment. That means you shouldn't change their names right now.
Configuring Database Settings for Cake
To configure database access, we edit config/database.php.default (he should have included the description himself) and save it as config/database.php. If config/database.php does not exist, cake still runs and does not use database access.
Create a model class (models in MVC)
Now create a model class for the Post table posts, and the new app/models/post.php contains the following:
app/models/post.php
Class Post extends Appmodel
{
}
?>
This is enough to get cake to focus on the model, load it, and connect it to the database table. Note: The class name of the model class is singular. It is important to adhere to the naming convention, because if this is not the case, cake will not run automatically. By default, model classes and database tables use the same word, while the former is singular and the latter is a plural form.
Set up a Controller helper class s
Create a new Controller helper class. Put the following in the app/helpers/posts_helper.php:
app/helpers/posts_helper.php
Class Postshelper extends AppController
{
}
?>
Create a Director Class (Controller)
Create a new controller class. Put the following in the app/controllers/posts_controller.php:
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
}
?>
The controller is ready, and this is where we need to add the action to manipulate the stored data. Add a method to the Postscontroller class:
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
Function index ()
{
}
}
?>
Postscontroller::index () does not require additional content, except for a template (called the "View" in cake).
Create a View
Put the following code into app/views/posts/index.thtml:
Blog posts
| Id |
Title |
Created |
Post->findall () as $post):?>
| |
LinkTo ($post [' title '], "/posts/view/{$post [' ID ']}")?>
|
|
This should work correctly, let's test it out. I assume you can get the cake directory by browsing http://localhost/cake/, so test our new controller, which points to http://localhost/cake/posts/index. You will (hopefully) see something similar to the following:
Blog posts
ID Title Created
1 the title 2005-07-03 10:52:21
2 A title once again 2005-07-03 10:52:34
3 Title Strikes Back 2005-07-03 10:52:43
Why didn't I see it??
If you encounter a page that says "not Found:the requested Url/posts/index is not Found on this server," You may want to use Http://localhost/cake/index. Php?url=posts to visit. Obviously, it's not beautiful. If you encounter a page that says "Fatal Error:call to a member function on a non-object ..." then you might want to check your configuration and have the Config/database.php.default renamed to Config/database.php. See the Blog Guide for faults and workarounds.
What have we done now?
Let's take a look back. We created the database table posts, a model class post, a controller Postscontroller and his index () method, and a view file app/views/posts/index.thtml. I don't think he is at all difficult. Let's go ahead.
The post title is connected to/cake/posts/view/[post_id]. Let's click on it.
Missing Action
You were seeing this error because the action was not defined in controller Posts
Notice:this error is being rendered by the app/views/errors/missing_action.thtml view file,
A user-customizable error page for handling invalid action dispatches.
Error:unable to execute action on Posts
Oh, yes, we forgot to add the Postscontroller::view () behavior. Let's finish it now:
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
Function index ()
{
}
function View ($id)
{
$this->models[' Post ']->setid ($id);
$this->set (' data ', $this->models[' post ']->read ());
}
}
?>
There are also view files:
App/views/posts/view.thtml
Created:
Back to the browser, refresh, see:
The title
created:2005-07-04 03:31:47
This is the post body.
It worked!
Add Features
After the first part of the guide, we have a list of posts and we can view the posts. When we have completed the second part, we can:
Add a new post.
Remove the posts you don't want.
Edit the existing post.
Add a new post
To add a new post:
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
Function index ()
{
}
function View ($id)
{
$this->models[' Post ']->setid ($id);
$this->set (' data ', $this->models[' post ']->read ());
}
function Add ()
{
if (Empty ($this->params[' data '))
{
$this->render ();
}
Else
{
if ($this->models[' post ']->save ($this->params[' data '))
{
$this->flash (' Your post has been saved. ', '/posts ');
}
Else
{
$this->set (' data ', $this->params[' data ');
$this->validateerrors ($this->models[' post ');
$this->render ();
}
}
}
}
?>
The template file for simultaneous behavior is:
App/views/posts/add.thtml
Add Post to Blog
Formtag ('/posts/add ')?>
Title: inputtag (' post/title ', +)?> tagerrormsg (' Post/title ', ' title is required. ')?>
Body: areatag (' body ')?> tagerrormsg (' post/body ', ' body is required. ')?>
Submittag (' Save ')?>
You can now access the Add page at the address "/cake/posts/add" via the "/cake/posts/add" url, or we can place a shortcut "Add new post" connection at the bottom of the index page:
App/views/posts/index.thtml
Blog posts
| Id |
Title |
Created |
Post->findall () as $post):?>
| |
LinkTo ($post [' title '], "/posts/view/{$post [' ID ']}")?>
|
|
LinkTo (' Add new post ', '/posts/add ')?>
Now let's try adding some posts.
As I have no rules, add a post without a title. Of course, we can avoid this incorrect behavior by data Validation.
Data validity
Data validation rules are placed in the data model.
app/models/post.php
Class Post extends Appmodel
{
var $validate = Array (
' Title ' =>valid_not_empty,
' Body ' =>valid_not_empty);
}
?>
Learn more about the Active verifier in the API documentation.
Delete a post
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
Function index ()
{
}
function View ($id)
{
$this->models[' Post ']->setid ($id);
$this->set (' data ', $this->models[' post ']->read ());
}
function Add ()
{
if (Empty ($this->params[' data '))
{
$this->render ();
}
Else
{
if ($this->models[' post ']->save ($this->params[' data '))
{
$this->flash (' Your post has been saved. ', '/posts ');
}
Else
{
$this->set (' data ', $this->params[' data ');
$this->validateerrors ($this->models[' post ');
$this->render ();
}
}
}
function Delete ($id)
{
if ($this->models[' post ']->del ($id))
{
$this->flash (' The Post with ID: '. $id. ' have been deleted. ', '/posts ');
}
}
}
?>
Delete behavior does not have a template. After the successful deletion, we just display a quick message (so-called "flash") and then back to the index page.
Now we add a delete behavior link to each blog post in the View:
App/views/posts/index.thtml
Blog posts
| Id |
Title |
Created |
Post->findall () as $post):?>
| |
LinkTo ($post [' title '], "/posts/view/{$post [' ID ']}")?> LinkTo (' Delete ', '/posts/delete/{$post [' ID ']} ", NULL," is sure you want to Delete post entitled \ ' {$post [' title ']}\ '? ")?>
|
|
LinkTo (' Add new post ', '/posts/add ')?>
After we finish it, we can delete the posts with the blank headers.
Edit a Post
app/controllers/posts_controller.php
Class Postscontroller extends Postshelper
{
Function index ()
{
}
function View ($id)
{
$this->models[' Post ']->setid ($id);
$this->set (' data ', $this->models[' post ']->read ());
}
function Add ()
{
if (Empty ($this->params[' data '))
{
$this->render ();
}
Else
{
if ($this->models[' post ']->save ($this->params[' data '))
{
$this->flash (' Your post has been saved. ', '/posts ');
}
Else
{
$this->set (' data ', $this->params[' data ');
$this->validateerrors ($this->models[' post ');
$this->render ();
}
}
}
function Delete ($id)
{
if ($this->models[' post ']->del ($id))
{
$this->flash (' The Post with ID: '. $id. ' have been deleted. ', '/posts ');
}
}
function edit ($id =null)
{
if (Empty ($this->params[' data '))
{
$this->models[' Post ']->setid ($id);
$this->params[' data ']= $this->models[' post ']->read ();
$this->render ();
}
Else
{
$this->models[' Post ']->set ($this->params[' data ');
if ($this->models[' post ']->save ())
{
$this->flash (' Your post has been updated. ', '/posts ');
}
Else
{
$this->set (' data ', $this->params[' data ');
$this->validateerrors ($this->models[' post ');
$this->render ();
}
}
}
}
?>
App/views/posts/edit.thtml
Edit Post to Blog
Formtag ('/posts/edit ')?>
Title: inputtag (' post/title ', +)?>
Tagerrormsg (' Post/title ', ' title is required. ')?>
Areatag (' body ')?>
Tagerrormsg (' post/body ', ' body is required. ')?>
Submittag (' Save ')?>
You can also do this with the Form tab
Hiddentag (' id ')?>
Instead of using HTML directly. Label.
Also, in index.thtml, we add an edit connection:
Blog posts
| Id |
Title |
Created |
Post->findall () as $post):?>
| |
LinkTo ($post [' title '], "/posts/view/{$post [' ID ']}")?> LinkTo (' Delete ', '/posts/delete/{$post [' ID ']} ", NULL," is sure you want to Delete post entitled \ ' {$post [' title ']}\ '? ")?> LinkTo (' Edit ', '/posts/edit/{$post [' ID ']} ")?>
|
|
LinkTo (' Add new post ', '/posts/add ')?>
Detach logic from a view
Let's look back at the index.thtml view:
App/views/posts/index.thtml
...
Post->findall () as $post):?>
...
We should remove the call to FindAll () from the view and put it in the controller. This can create a better separation of logic and views. Then we get the data from the controller back to the view. Now let's finish it.
In the controller of the post, we get all the records from the posts model and store them in the variable data.
app/controllers/posts_controller.php
...
Function index ()
{
$this->set (' data ', $this->models[' post ']->findall ());
}
...
?>
At the same time in the view, we show all of his content by iterating over each row of data.
App/views/posts/index.thtml
...
...
It's too easy, isn't it?