LoginSignup
0
0

More than 5 years have passed since last update.

【CakePHP2】サイトを作る【MQ01】

Last updated at Posted at 2017-01-27

概要

CakePHPの2系に触れてから2ヶ月ほど経ち、今までやった事を1つ1つまとめておこうと思います。
MQというのはなんとなく順番が分かるように、です。

初回である今回は、サイトを作る基本の3通りの方法をまとめておきます。

環境はWindowsのPuTTYからCakePHP2.9.4、さくらのレンタルサーバでFreeBSDを使っています。

インストールとか、データベースの初期設定は他のサイトを見て下さい。

基本であるapp下だけ触る感じです。

DBテーブルはさくらのphpMyAdminから「cards」というものを作った場合です。
構造はid,name,body,created,modifiedだけです。
スクリーンショット 2017-01-25 15.01.06.png

Scaffoldの場合

Controller/CardsController.php
<?php

class CardsController extends AppController {

    public $scaffold;

}
Model/Card.php
<?php

class Card extends AppController {
    // 何もなくておk
}

これだけです。
もし出来なかったら、キャッシュの問題かもです。
http://weble.org/2011/01/01/cakephp-table-cache
自分はこれで1回やられました。

Bakeする場合

.bashrcに設定しておくとラクですね。
cake.phpまでのフルパスで

.bashrc
alias cake='php /home/(略)/cake/cakephp/lib/Cake/Console/cake.php'

設定した後は、cake bake allとどこからでも打ち込めて、好きなデータベーステーブル選んで……って出来るはず。

データベースのカラムにあらかじめuser_idとかを入れておくと、このbakeで紐付け(アソシエーション)の設定してくれたりします。

自分でファイルを作る場合

bakeされたものを見た方が良い気もしますが……、まぁ参考になれば。
Viewでpr()とかdebug()とかを使ってデータの中身を見ると、表示の方法をイメージ掴みやすくなっていいと思います。

あとオマケですが、良く使うarray()[]でもいいらしいです。

基本はControllerでアクション追加して、同じ名前のctpファイルをViewに作るというだけですね。

Model

Model.Card.php
<?php

class Card extends AppModel {
    // 何も無し 
}

Controller

Controller/CardsController.php

<?php

class CardsController extends AppController {

    // public $scaffold;

    var $uses = array('Card'); // 使うModelの設定

    public function index() {
        $datas = $this->Card->find('all'); // データを取得

        $this->set(compact('datas')); // Viewにデータを渡す
        // $this->set('datas',$datas); // 上はこれと同じ意味
    }


    // 以降、ほぼbakeそのまま

    public function add() {
        // POSTだったら
        if ($this->request->is('post')) {
            $this->Card->create(); // Modelの中身をリセット

            // if文の中でセーブ処理
            // 上手くいったらTrueが返るんでしょう。多分
            if ($this->Card->save($this->request->data)) {
                $this->Flash->success(__('The card has been saved.'));
                return $this->redirect(array('action' => 'index')); // indexに戻る
            } else {
                $this->Flash->error(__('The card could not be saved.'));
            }

        }
    }

    public function view($id = null) {
        // 渡されたidのデータが無かったらエラー
        if (!$this->Card->exists($id)) {
            throw new NotFoundException(__('Invalid Card'));
        }

        $options = array(
            'conditions' => array(
                'Card.id' => $id
            )
        );
        $this->set('data', $this->Card->find('first', $options));
    }

    public function edit($id = null) {
        if (!$this->Card->exists($id)) {
            throw new NotFoundException(__('Invalid card'));
        }

        if ($this->request->is(array('card', 'put'))) {
            if ($this->Card->save($this->request->data)) {
                $this->Flash->success(__('The card has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Flash->error(__('The card could not be saved. Please, try again.'));
            }
        } else {
            $options = array(
                'conditions' => array(
                    'Card.' . $this->Card->primaryKey => $id
                )
            );
            $this->request->data = $this->Card->find('first', $options);
        }
    }

}

View

View/Cards/index.ctp
<div class="index">

<h2>Cards Index</h2>

<table>

    <tr>
        <th>ID</td>
        <th>名前</td>
        <th>内容</td>
        <th>作成日</td>
        <th>更新日</td>
        <th>Actions</td>
    </tr>

<?php foreach($datas as $data): ?>
    <tr>
        <td><?php echo h($data['Card']['id']); ?></td>
        <td><?php echo h($data['Card']['name']); ?></td>
        <td><?php echo h($data['Card']['body']); ?></td>
        <td><?php echo h($data['Card']['created']); ?></td>
        <td><?php echo h($data['Card']['modified']); ?></td>
        <td class="actions">
            <?php
            echo $this->Html->link(__('View'), array(
                'action' => 'view', 
                $data['Card']['id']
            )); 
            echo $this->Html->link(__('Edit'), array(
                'action' => 'edit', 
                $data['Card']['id']
            ));
            ?>
        </td>
    </tr>
<? endforeach; ?>

</table>

<h3>データの中身</h3>
<?php
    pr($datas); // 中身確認すると扱い方がすごく良く分かる
    // debug()でも似た感じ
?>

</div>

<div class="actions">
    <h3><?php echo __('Actions'); ?></h3>
    <ul>
        <li>
        <?php 
            echo $this->Html->link(__('New Card'), array(
                'controller' => 'cards', 
                'action' => 'add'
            ));
        ?> 
        </li>
    </ul>
</div>
View/Cards/add.ctp
<?php
    // 基本いつでもechoが必要なので忘れずに!
    echo $this->Html->link('一覧に戻る',[
        'controller' => 'Cards',
        'action' => 'index',
    ]);
?>

<br><br><br>

<h2>
新規カードを登録
</h2>

<?php
    echo $this->Form->create('Card');
    echo $this->Form->input('name',array(
        'label' => 'カード名',
    ));
    echo $this->Form->input('body',array(
        'label' => '内容',
    ));
    echo $this->Form->end(__('登録')); 
?>
View/Cards/view.ctp
<div class="cards view">
<h2>Card</h2>
    <dl>
        <dt><?php echo __('Id'); ?></dt>
        <dd>
            <?php echo h($data['Card']['id']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Name'); ?></dt>
        <dd>
            <?php echo h($data['Card']['name']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Body'); ?></dt>
        <dd>
            <?php echo h($data['Card']['body']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Created'); ?></dt>
        <dd>
            <?php echo h($data['Card']['created']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Modified'); ?></dt>
        <dd>
            <?php echo h($data['Card']['modified']); ?>
            &nbsp;
        </dd>
    </dl>
</div>
<div class="actions">
    <h3><?php echo __('Actions'); ?></h3>
    <ul>
        <li><?php echo $this->Html->link(__('Edit Card'), array('action' => 'edit', $data['Card']['id'])); ?> </li>
        <li><?php echo $this->Html->link(__('List Card'), array('action' => 'index')); ?> </li>
        <li><?php echo $this->Html->link(__('New Card'), array('action' => 'add')); ?> </li>
    </ul>
</div>
View/Cards/edit.ctp
<div class="cards form">
<?php echo $this->Form->create('Card'); ?>
    <fieldset>
        <legend><?php echo __('Edit Card'); ?></legend>
    <?php
        // idは要らないように見えるけど無いとaddになる
        echo $this->Form->input('id'); 
        echo $this->Form->input('name');
        echo $this->Form->input('body');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

<div class="actions">
    <h3><?php echo __('Actions'); ?></h3>
    <ul>
        <li><?php echo $this->Html->link(__('List Card'), array('action' => 'index')); ?></li>
    </ul>
</div>

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0