cakephp官方 blog实例
The Cake Blog Tutorial—在网上找了好多的教程,没有一个满意的,最后还是到官方网站得到想要的.
Section 1
Here’s what you’ll need需要的一些服务器配置)
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.
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 reigns from there.
Basic PHP knowledge. The more object-oriented programming you’ve done, the better: but fear not if you’re a procedural fan.
Finally, you’ll need a basic knowledge of the MVC programming pattern. A quick overview can be found in Chapter "Basic Concepts", Section 2: The MVC Pattern. Don’t worry: its only a half a page or so.
Section 2
下载最新的cakephp版本:http://cakeforge.org/projects/cakephp/
You can also checkout/export a fresh copy of our trunk code at: https://svn.cakephp.org/repo/trunk/cake/1.x.x.x/
将代码整个cakephp文章放到根目录下,这里的结构如下:
/path_to_document_root
/app
/cake
/vendors
.htaccess
index.php
VERSION.txt
Section 3
创建blog的所需数据库,执行一下sql代码:
/* 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)
VALUES (’Title strikes back’, ‘This is really exciting! Not.’, NOW());
Section 4
配置数据库:
A copy of Cake’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.将app/config/database.php.default复制一份,然后将其改名为database.php,并将其中的数据库的相关配置配成你的相应的信息.
class DATABASE_CONFIG {
var $default = array(
‘driver’ => ‘mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘port’ => ”,
‘login’ => ‘root’,
‘password’ => ”,
‘database’ => ‘cakeblog’,
’schema’ => ”,
‘prefix’ => ”,
‘encoding’ => ”
);
}
Section 5
对于url的rewrite_model的配置
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.
Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.
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.
Make sure you are loading up mod_rewrite correctly! You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so and 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:
define (’BASE_URL’, env(’SCRIPT_NAME’));
This will make your URLs look like www.example.com/index.php/controllername/actionname/param rather than www.example.com/controllername/actionname/param.
Section 6
创建blog的post模型/app/models/post.php 复制内容到剪贴板
代码:
<?php
class Post extends AppModel
{
var $name = ‘Post’;
}
?>由我们给定的模型名称可以看出,模型名称和你的控制器名称是相对应的,例如model/post.php,则控制器为controllers/posts_Controller.php,同样,这个还与我们的数据库的表相关联,这个同时告诉我们我们所使用的数据库为posts.如果还有问题的话,可以查看模型的相关说明: Chapter "Models".
Section 7
创建一个posts的控制方法:/app/controllers/posts_controller.php 复制内容到剪贴板
代码:
<?php
class PostsController extends AppController
{
var $name = ‘Posts’;
}
?>添加一个默认的action动作,用于显示首页信息:
/app/controllers/posts_controller.php (index action added) 复制内容到剪贴板
代码:
<?php
class PostsController extends AppController
{
var $name = ‘Posts’;
function index()
{
$this->set(’posts’, $this->Post->findAll());
}
}
?>如果对于controllers有不明白的地方可以查看:Chapter "Controllers".
Section 8
创建posts的视图模型,我们可以在调试时同时输出我们的数据,使用 print_r($posts)可以输出以下的格式:
// print_r($posts) output:
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => The title
[body] => This is the post body.
[created] => 2006-03-08 14:42:22
[modified] =>
)
)
[1] => Array
(
[Post] => Array
(
[id] => 2
[title] => A title once again
[body] => And the post body follows.
[created] => 2006-03-08 14:42:23
[modified] =>
)
)
[2] => Array
(
[Post] => Array
(
[id] => 3
[title] => Title strikes back
[body] => This is really exciting! Not.
[created] => 2006-03-08 14:42:24
[modified] =>
)
)
)
创建视图的默认文件index.thtml:/app/views/posts/index.thtml 复制内容到剪贴板
代码:
<h1>Blog posts</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!– Here’s 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>添加浏览动作:/app/controllers/posts_controller.php (view action added) 复制内容到剪贴板
代码:
<?php
class PostsController extends AppController
{
var $name = ‘Posts’;
function index()
{
$this->set(’posts’, $this->Post->findAll());
}
function view($id = null)
{
$this->Post->id = $id;
$this->set(’post’, $this->Post->read());
}
}
?>创建视图浏览页面:/app/views/posts/view.thtml 复制内容到剪贴板
代码:
<h1><?php echo $post[’Post’][’title’]?></h1>
<p><small>Created: <?php echo $post[’Post’][’created’]?></small></p>
<p><?php echo $post[’Post’][’body’]?></p>Verify that this is working by trying the links at /posts/index or manually requesting a post by accessing /posts/view/1.
Section 9
创建添加blog的动作:/app/controllers/posts_controller.php (add action added) 复制内容到剪贴板
代码:
<?php
class PostsController extends AppController
{
var $name = ‘Posts’;
function index()
{
$this->set(’posts’, $this->Post->findAll());
}
function view($id)
{
$this->Post->id = $id;
$this->set(’post’, $this->Post->read());
}
function add()
{
if (!empty($this->data))
{
if ($this->Post->save($this->data))
{
$this->flash(’Your post has been saved.’,'/posts’);
}
}
}
}
?>Let me read the add() action for you in plain English: if the form data isn’t empty, try to save the post model using that data. If for some reason it doesn’t save, give me the data validation errors and render the view showing those errors.
When a user uses a form to POST data to your application, that information is available in $this->params. You can pr() that out if you want to see what it looks like. $this->data is an alias for $this->params[’data’].
The $this->flash() function called is a controller function that flashes a message to the user for a second (using the flash layout) then forwards the user on to another URL (/posts, in this case). If DEBUG is set to 0 $this->flash() will redirect automatically, however, if DEBUG > 0 then you will be able to see the flash layout and click on the message to handle the redirect.
Calling the save() method will check for validation errors and will not save if any occur. There are several methods available so you can check for validation errors, but we talk about the validateErrors() call in a bit, so keep that on the back burner for a moment while I show you what the view looks like when we move on to the section about data validation.
Section 10
Data Validation
创建一个添加blog的视图:/app/views/posts/add.thtml 复制内容到剪贴板
代码:
<h1>Add Post</h1>
<form method="post" action="<?php echo $html->url(’/posts/add’)?>">
<p>
Title:
<?php echo $html->input(’Post/title’, array(’size’ => ‘40′))?>
<?php echo $html->tagErrorMsg(’Post/title’, ‘Title is required.’) ?>
</p>
<p>
Body:
<?php echo $html->textarea(’Post/body’, array(’rows’=>’10′)) ?>
<?php echo $html->tagErrorMsg(’Post/body’, ‘Body is required.’) ?>
</p>
<p>
<?php echo $html->submit(’Save’) ?>
</p>
</form>添加表单的数据验证规则:/app/models/post.php (validation array added) 复制内容到剪贴板
代码:
<?php
class Post extends AppModel
{
var $name = ‘Post’;
var $validate = array(
‘title’ => VALID_NOT_EMPTY,
‘body’ => VALID_NOT_EMPTY
);
}
?>The $validate array tells Cake how to validate your data when the save() method is called. The values for those keys are just constants set by Cake that translate to regex matches (see /cake/libs/validators.php). Right now Cake’s validation is regex based, but you can also use Model::invalidate() to set your own validation dynamically.
Section 11
删除动作:/app/controllers/posts_controller.php (delete action only) 复制内容到剪贴板
代码:
function delete($id)
{
$this->Post->del($id);
$this->flash(’The post with id: ‘.$id.’ has been deleted.’, ‘/posts’);
}现在首页添加add和delete的链接:/app/views/posts/index.thtml (add and delete links added) 复制内容到剪贴板
代码:
<h1>Blog posts</h1>
<p><?php echo $html->link(’Add Post’, ‘/posts/add’); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!– Here’s 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’]);?>
<?php echo $html->link(
‘Delete’,
"/posts/delete/{$post[’Post’][’id’]}",
null,
‘Are you sure?’
)?>
</td>
</td>
<td><?php echo $post[’Post’][’created’]; ?></td>
</tr>
<?php endforeach; ?>
</table>Section 12
添加编辑动作edit:/app/controllers/posts_controller.php (edit action only) 复制内容到剪贴板
代码:
function edit($id = null)
{
if (empty($this->data))
{
$this->Post->id = $id;
$this->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->data[’Post’]))
{
$this->flash(’Your post has been updated.’,'/posts’);
}
}
}编辑视图模板文件:/app/views/posts/edit.thtml 复制内容到剪贴板
代码:
<h1>Edit Post</h1>
<form method="post" action="<?php echo $html->url(’/posts/edit’)?>">
<?php echo $html->hidden(’Post/id’); ?>
<p>
Title:
<?php echo $html->input(’Post/title’, array(’size’ => ‘40′))?>
<?php echo $html->tagErrorMsg(’Post/title’, ‘Title is required.’) ?>
</p>
<p>
Body:
<?php echo $html->textarea(’Post/body’, array(’rows’=>’10′)) ?>
<?php echo $html->tagErrorMsg(’Post/body’, ‘Body is required.’) ?>
</p>
<p>
<?php echo $html->submit(’Save’) ?>
</p>
</form>最后添加首页的编辑链接:/app/views/posts/index.thtml (edit links added) 复制内容到剪贴板
代码:
<h1>Blog posts</h1>
<p><?php echo $html->link("Add Post", "/posts/add"); ?>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!– Here’s 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’]);?>
<?php echo $html->link(
‘Delete’,
"/posts/delete/{$post[’Post’][’id’]}",
null,
‘Are you sure?’
)?>
<?php echo $html->link(’Edit’, ‘/posts/edit/’.$post[’Post’][’id’]);?>
</td>
</td>
<td><?php echo $post[’Post’][’created’]; ?></td>
</tr>
<?php endforeach; ?>
</table>Section 13
路由设置附带)
This part is optional, but helpful in understanding how URLs map to specific function calls in Cake. We’re only going to make a quick change to routes in this tutorial. For more information, see Chapter "Configuration", Section 3: Routes Configuration.
Cake’s default route will take a person visiting the root of your site (i.e. http://www.example.com) to the PagesController, and render a view called home. Rather than do that, we’ll want users of our blog application to go to our soon-to-be-created PostsController.
Cake’s routing is found in /app/config/routes.php. You’ll want to comment out or remove the line that looks like this:
$Route->connect (’/', array(’controller’=>’pages’, ‘action’=>’display’, ‘home’));
This line connects the URL / with the default Cake home page. We want it to connect with our own controller, so add a line that looks like this:
$Route->connect (’/', array(’controller’=>’posts’, ‘action’=>’index’));
This should connect users requesting ‘/’ to the index() action of our soon-to-be-created PostsController.
此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/766.html