※当サイトの記事には、広告・プロモーションが含まれます。

PHP CakePHP(バージョン2.6.4)というフレームワーク

フレームワークMVCの原則に従うことから、アプリケーションのほとんどの側面に於いてカスタマイズ・拡張が簡単にできるようになります。このフレームワークはファイル名からデータベースのテーブル名まで、基礎的な組織構造も提供し、アプリケーション全体を矛盾無く論理的に保ちます。規約に従うことで、どこに何があるのか、それらがどのように組織化されているのかを、いつも確実に把握できるのです。

 MVC(Model-View-Controller) ⇒ 

モデル(Model)層 ⇒ データベースの関係性の構築。
ビュー(View)層 ⇒ ブラウザ上に表示されるHTMLなど。
コントローラ(Controller)層 ⇒ ページごとの処理。

特徴

 命名規則がある。

テーブルは複数系(例:posts)

テーブル名とファイル名を統一する。

varcharとtextの違い

textは改行ができる。

データベースのデータ型に合わせてformの型を自動で作成してくれる。

MySQLの他にSQLitePostgreSQLSQL Serverなどが利用できます。

ブログチュートリアル

CakePHPのダウンロード

下記サイトでCakePHP2.6.4をダウンロード。

CakePHP:高速開発 phpフレームワーク。Home

ダウンロードしたzipファイルを解凍して、デスクトップに置きます。

ブログデータベースの作成

ブログで使用する基礎的なデータベースをセットアップしましょう。 データベースをまだ作成していないのであれば、このチュートリアル用に好きな名前で空のデータベースを作成しておいてください。

今回はデータベース名『cakePHP』を作成しました。

投稿記事を保存するためのテーブルをひとつ作成します。 次のSQLをデータベースで実行してください。

phpMyAdminで行う際は、postsテーブルを作成のSQLは『cakePHP』を選んで実行、テスト用の記事を挿入するSQLは作成した『posts』テーブルを選んだ状態で実行。

 

/* まず、postsテーブルを作成します: */
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

/* それから、テスト用に記事をいくつか入れておきます: */
INSERT INTO posts (title,body,created)
    VALUES ('タイトル', 'これは、記事の本文です。', NOW());
INSERT INTO posts (title,body,created)
    VALUES ('またタイトル', 'そこに本文が続きます。', NOW());
INSERT INTO posts (title,body,created)
    VALUES ('タイトルの逆襲', 'こりゃ本当にわくわくする!うそ。', NOW());

Cakeのデータベース設定

app/Config/database.php.defaultをdatabase.phpに名前を変えて、ファイルの中身の下記の部分を自分の情報に変えて保存する。

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost', //xamppの場合localhost
    'port' => '',
    'login' => 'cakeBlog',
    'password' => 'root',  //xamppの場合Mysql(phpMyAdmin)のログインの時のパスワード
    'database' => 'cakePHP', //データベース名
    'schema' => '',
    'prefix' => '',
    'encoding' => 'utf8'  //文字コード
);

 データベース接続エラーが消えます。

Security.saltとSecurity.cipherSeedの設定

下記サイトで表示されてる値をcore.phpの下記部分に貼り付けます。

[CakePHP] Security.salt 生成ツール変換商社

 

core.php

* A random string used in security hashing methods.
*/
Configure::write('Security.salt', ' ここの部分に貼り付け ');

/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
Configure::write('Security.cipherSeed', ' ここの部分に貼り付け ');

 

デバックキットのダウンロード

 GitHubでダウンロードしたzipフォルダを解凍してデスクトップに置きます。

フォルダ名を『DebugKit』にしてhtdocs/app/Pluginの中に移動します。

デバックキットをCakePHPで使えるようにします。

 

app/Config/bootstrap.phpbootstrap.phpファイルの以下の部分のコメントアウトを解除します。

テラパッドで開いた場合は69行目に記述されてる部分。

CakePlugin::load('DebugKit');

デバックの機能はvar_dump( )などを使えるようにしているもの。

ブログチュートリアル - レイヤーの追加

モデルクラスは、CakePHPアプリケーションの基本中の基本(bread and butter)です。 CakePHPのモデルを作成することで、データベースとやりとりできるようになり、表示(view)、追加(add)、編集(edit)、削除(delete)といった操作に必要な土台を手に入れることになります。

Postモデルの作成

Post.phpを作成しapp』フォルダの中の『Model』フォルダの中に保存。

Post.php

 CakePHPのモデルクラスのファイルは、 /app/Model の中にあり、今回は、 /app/Model/Post.php というファイルを作って保存します。

class Post extends AppModel {
}

Postsコントローラの作成

 PostsControllerを作成し『app』フォルダの中の『Controller』フォルダの中に保存。

PostsController.php

/* topページを追加する。index.phpというページを生成。postsという変数にテーブルのPostの情報を全て取得し代入。setでHTML表示。*/

PostsController.php という名前で、 /app/Controller ディレクトリの中に配置します。

class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

 

Postビューの作成

『app』フォルダの中の『View』フォルダの中に『Posts』フォルダを作成し『index.ctp』ファイルを作成し保存。

(ctpはcake template phpの略。)

index.ctp

 /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>

    <!-- ここから、$posts配列をループして、投稿記事の情報を表示 -->

    <?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>

ブラウザのアドレスバーにlocalhost/postsと入力し表示させる。

default.ctpがwordpressでいうところのheader.phpやfooter.phpなどのファイルがまとめてあるところ。

 個別ページ表示

PostsController.phpに追加記述。

『app』フォルダの中の『Controller』フォルダの中の『PostsController.php』ファイルに記述。

PostsController.php

   /app/Controller/PostsController.php

// File: /app/Controller/PostsController.php
class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
         $this->set('posts', $this->Post->find('all'));
    }

    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);
    }
}

これでタイトルをクリックすると個別ページを表示できるようになります。

存在する記事のみにアクセスさせるための記述

 /app/View/Posts/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>

記事の追加

PostController.phpにadd( )を追加記述。

PostController.php

   /app/Controller/PostsController.php

class PostsController extends AppController {
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }

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

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

    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.'));
        }
    }
}

データのバリデーション

バリデーション

⇒規定された要求事項がその記述された使用に対して適切であることを検証すること。

『app』フォルダの中の『View』フォルダの中の『Posts』フォルダの中の『add.ctp』ファイルに記述。

add.ctp

バリデーションの機能を活用するためには、ビューの中でCakeのFormHelperを使う必要があります。 FormHelper はデフォルトで、すべてのビューの中で $this->Form としてアクセスできるようになっています。

<!-- 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');
?>

 ここで、FormHelperを使って、HTMLフォームの開始タグを生成しています。 $this->Form->create() が生成したHTMLは次のようになります:

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

Helper(ヘルパー)について

「Add Post」というリンクを新しく表示

 『app』フォルダの中の『View』フォルダの中の『Posts』フォルダの中の『index.ctp』ファイルの<table> の前に記述。

index.ctp

/app/View/Posts/index.ctp

<?php echo $this->Html->link(
    'Add Post',
    array('controller' => 'posts', 'action' => 'add')
); ?>

バリデーションのルールは、モデルの中で定義することができます

$validate 配列を使って、 save( ) メソッドが呼ばれた時に、どうやってバリデートするかをCakePHPに教えます。

『app』フォルダの中の『Model』フォルダの中の『Post.php』ファイルに記述。

Post.php

  /app/Model/Post.php

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

投稿記事の編集

PostsController.phpに edit( )を追加記述。

 『app』フォルダの中の『Controller』フォルダの中の『PostsController.php』ファイルに記述。

PostsController.php

   /app/Controller/PostsController.php

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;
    }
}

編集フォームを出力するeditヴューの作成。

『app』フォルダの中の『View』フォルダの中の『Posts』フォルダの中に『edit.ctp』ファイルを作成。

/app/View/Posts/edit.ctp

<!-- 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');
?>

特定の記事をアップデートするためのリンクをindexビューに追加。

『app』フォルダの中の『View』フォルダの中の『Posts』フォルダの中の『index.ctp』ファイルに追加記述。

index.ctp

/app/View/Posts/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>Action</th>
        <th>Created</th>
    </tr>

<!-- $post配列をループして、投稿記事の情報を表示 -->

<?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td>
        <td>
            <?php echo $this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['id'])); ?>
        </td>
        <td>
            <?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Post']['id'])); ?>
        </td>
        <td>
            <?php echo $post['Post']['created']; ?>
        </td>
    </tr>
<?php endforeach; ?>

</table>

投稿記事の削除

PostsController.phpにdelete( )を追加記述。

 『app』フォルダの中の『Controller』フォルダの中の『PostsController.php』ファイルに記述。

PostsController.php

    /app/Controller/PostsController.php

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))
        );
    } else {
        $this->Session->setFlash(
            __('The post with id: %s could not be deleted.', h($id))
        );
    }

    return $this->redirect(array('action' => 'index'));
}

 indexビューにリンクを付けて、投稿を削除できるようにする。

『app』フォルダの中の『View』フォルダの中の『Posts』フォルダの中の『index.ctp』ファイルに追加記述。

index.ctp

/app/View/Posts/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>

<!-- ここで$posts配列をループして、投稿情報を表示 -->

    <?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td>
        <td>
            <?php echo $this->Html->link($post['Post']['title'], array('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>

ルーティング(Routes)

Cakeのルーティングは、 /app/Config/routes.php の中にあります。 デフォルトのトップページのルートをコメントアウトするか、削除します。 この行です:

Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));

 この行は、「/」というURLをデフォルトのCakePHPのホームページに接続します。 これを、自分のコントローラに接続させるために、次のような行を追加してください:

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

 これで、「/」でリクエストしてきたユーザを、PostControllerのindex()アクションに接続させることができます。

 以上の情報はCakePHPの公式ページに詳しく載ってます。

CakePHPブログチュートリアル