hetemlでのcakephpインストール&掲示板アプリ作成方法その2

f:id:tsumayouzi:20150222151344j:plain

簡単な掲示板を作成してcakephpでの仕組みを把握しようとした備忘録

1  デフォルトで反映されているデザインを一旦リセット

/cakePHPのディレクトリ/app/views/layouts/default.ctpを編集 (.ctp?cake templateの略なのか。tmpファイル等と同じような扱いっぽい??)

<!DOCTYPE html> <?<a class="keyword" href="http://d.hatena.ne.jp/keyword/php">php</a> echo $title_for_layout; ?> <?php echo $content_for_layout; ?>

2 ホーム画面を変更 

/cakePHPのディレクトリ/app/config/routes.phpを編集 30行目付近の1行をこのように変更

Router::connect('/', array('controller' => '任意のページ名A', 'action' => 'index', 'home'));

3 /cakePHPのディレクトリ/任意のページ名Aにアクセス

するとこのようなエラー文が(newpageというページ名にしました。) f:id:tsumayouzi:20150222223604p:plain 怒られています。phpはjsと違って公開処刑でつらい。挫折しそう。

4 C:コントローラーを作成

/cakePHPのディレクトリ/app/Controller/任意のページ名AController.ctp という空の.ctpを作成し、

<?php class 任意のページ名AController extends AppController {

var $name = 'Posts';

public function index() {

  //sql
  $results = $this->Post->find('all' , array('order' => 'id desc' ));
  $this->set('results',$results);

} public function display() {

}

}

5 V:ビューを作成

/cakePHPのディレクトリ/app/View/任意のページ名A/index.ctp ディレクトリ&空のindex.ctpを作成 <!DOCTYPE HTML>~等は1で作成した/app/views/layouts/default.ctpで定義しているので、body内のみでokの模様。

<?php var_dump($results); //中身を出力

foreach($results as $post){ echo "

{$post['Post']['カラム名']}

"; } ?>

6 ホーム画面(/cakePHPのディレクトリ/)へアクセス

おそらく無事に出力部分が完成しました。 f:id:tsumayouzi:20150222225957p:plain

ビューで急に出てきた変数$resultsはコントローラー部分で使った変数がそのまま使える模様。 生のphpでゴリゴリ書くときに、classでリターンで返していた手間が省けてすごい便利。 よくメリットとして聞いたビューはデザイナーに。コントローラの作成はシステム側にという分業が本当にしやすそう。