PHP框架之CakePHP(一)

CakePHP是一個運用了諸如ActiveRecord、Association Data Mapping、Front Controller和MVC等著名設計模式的快速開發框架。php

下面就用PHP快速搭建一個Blog網站。git

1、獲取CakePHP代碼github

首先下載一個CakePHP框架代碼也能夠直接使用git去獲取代碼,git庫地址是:git://github.com/cakephp/cakephp.gitsql

 

2、建立數據庫數據庫

這裏的示例博客網站是基於WAMP的,所以先創建一個博客數據庫,只有一個表postsapache

/* 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'能夠直接調用默認的方法。設計模式

 

3、CakePHP數據庫配置和其餘配置app

在代碼相應目錄找到/app/Config/database.php.default命名框架

名爲database.php,修改其中的配置爲本身電腦的配置dom

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增長一個對應的站點。

 

4、下面就能夠建立博客程序了

博客實現一個簡單的增刪改查操做

首先砸/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

相關文章
相關標籤/搜索