PHP框架之CakePHP(一)

CakePHP是一个运用了诸如ActiveRecord、Association Data Mapping、Front Controller和MVC等著名设计模式的快速开发框架。

下面就用PHP快速搭建一个Blog网站。

一、获取CakePHP代码

首先下载一个CakePHP框架代码也可以直接使用git去获取代码,git库地址是:git://github.com/cakephp/cakephp.git

 

二、创建数据库

这里的示例博客网站是基于WAMP的,因此先建立一个博客数据库,只有一个表posts

/* First, create 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());

表名和字段名称不是特定的,但如果要遵循CakePHP的数据库命名规范和CakePHP类的命名规范,你可以利用很多免费的功能,初学时可以节省很多的时间,表命名为'posts'后自动绑定相应的模型,字段为'modified'和'created'可以直接调用默认的方法。

 

三、CakePHP数据库配置和其他配置

在代码相应目录找到/app/Config/database.php.default命名

名为database.php,修改其中的配置为自己电脑的配置

public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => '123456',
        'database' => 'cakephp',
        'prefix' => '',
        'encoding' => 'utf8',
    );

保存即成功配置了数据库其他可选配置:/app/Config/core.php,这是某些加密随机数配置

/**
 * A random string used in security hashing methods.
 */
Configure::write('Security.salt', '8a9sdjox099f0aj0j');


/**
 * A random numeric string (digits only) used to encrypt/decrypt strings.
 */
Configure::write('Security.cipherSeed', '73825092878042703');
 

保证目录app/tmp是可写的,一般在Windows环境下都不会存在权限问题。

另外要对apache进行配置,保证apache的rewrite模块开启 找到#LoadModule rewrite_module modules/mod_rewrite.so行将前面的#去掉,重启后生效。

在apache增加一个对应的站点。

 

四、下面就可以创建博客程序了

博客实现一个简单的增删改查操作

首先砸/app/Model/路径下创建一个新的模块Post.php

class Post extends AppModel {
}

首先在/app/Controller/路径下创建一个新的控制器PostsController.php文件,并为这个控制器增加一个默认行为。

class PostsController extends AppController {
    public $helpers = array('Html', 'Form');
    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

在/app/View路径下创建一个模板目录Posts/,再创建一个模板文件index.ctp

<!-- File: /app/View/Posts/index.ctp -->

<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 $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
        </td>
        <td><?php echo $post['Post']['created']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($post); ?>
</table>

浏览单个文章时,通过Id来获取文章内容,再在上面控制器中增加一个view方法

public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }

        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }

对应的模板文件view.ctp

<!-- File: /app/View/Posts/view.ctp -->

<h1><?php echo h($post['Post']['title']); ?></h1>

<p><small>Created: <?php echo $post['Post']['created']; ?></small></p>

<p><?php echo h($post['Post']['body']); ?></p>

增加add,对应的方法

public function add() {
        if ($this->request->is('post')) {
            $this->Post->create();
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }

模板文件add.ctp

<!-- File: /app/View/Posts/add.ctp -->

<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>

这里使用了一个form表单,$this->Form->create('Post'),相当与创建了一个这样的表单区域

<form id="PostAddForm" method="post" action="/posts/add">

CakePHP是怎样进行表单验证的呢,在/app/Model/Post.php中创建一个表单验证规则即可进行表单验证:

class Post extends AppModel {
    public $name = 'Post';
    
    public $validate = array(  
        'title' => array(  
            'rule' => 'notEmpty'  
        ),  
        'body' => array(  
            'rule' => 'notEmpty'  
        )  
    );  
}

增加编辑功能

public function edit($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }

    if ($this->request->is(array('post', 'put'))) {
        $this->Post->id = $id;
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been updated.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to update your post.'));
    }

    if (!$this->request->data) {
        $this->request->data = $post;
    }
}

和编辑页面

<!-- File: /app/View/Posts/edit.ctp -->

<h1>Edit Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Post');
?>

再增加删除功能

public function delete($id) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }

    if ($this->Post->delete($id)) {
        $this->Session->setFlash(__('The post with id: %s has been deleted.', h($id)));
        return $this->redirect(array('action' => 'index'));
    }
}

在上面的index.ctp文件中增加编辑、删除按钮

<!-- File: /app/View/Posts/index.ctp -->  
<h1>Blog posts</h1>  
<p><?php echo $this->Html->link('Add Post', array('action' => 'add')); ?></p> 
<table>  
    <tr>  
        <th>Id</th>  
        <th>Title</th> 
        <th>Actions</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 $this->Html->link($post['Post']['title'],  
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>  
        </td>  
        <td>  
            <?php echo $this->Form->postLink(  
                'Delete',  
                array('action' => 'delete', $post['Post']['id']),  
                array('confirm' => 'Are you sure?'));  
            ?>  
            <?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Post']['id']));?> 
        </td>   
        <td><?php echo $post['Post']['created']; ?></td>  
    </tr>  
    <?php endforeach; ?>  
</table>

一个简单的博客页面就创建完成了。

找到/app/Config/routes.php文件修改下默认的路径为

Router::connect('/', array('controller' => 'posts', 'action' => 'index'));

即可默认直接访问到博客首页。

image

转载于:https://www.cnblogs.com/lovett/p/3436270.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值