MVCを一気に作成するbakeコマンド
[vagrant@localhost myapp]$ bin/cake bake all posts [vagrant@localhost myapp]$ bin/cake server -H 192.168.33.10 -p 8000
データベースの条件抽出
class PostsController extends AppController
{
public function index()
{
$posts = $this->Posts->find('all')
->order(['title' => 'DESC'])
->limit(2)
->where(['title like' => '%3']);
$this->set('posts', $posts);
}
}
デフォルトレイアウト
src->Template->Layout->default.ctp
レイアウトのカスタマイズ
<!DOCTYPE html>
<html lang="ja">
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $cakeDescription ?>:
<?= $this->fetch('title') ?>
</title>
<?= $this->Html->css('styles.css') ?>
</head>
<body>
<div class="container">
<?= $this->fetch('content') ?>
</div>
</body>
</html>
PostsController.phpの編集
class PostsController extends AppController
{
public function index()
{
$this->viewBuilder()->layout('my_layout');
$posts = $this->Posts->find('all');
// ->order(['title' => 'DESC'])
// ->limit(2)
// ->where(['title like' => '%3']);
$this->set('posts', $posts);
}
}
cssファイルはwebroot/cssにあります。
titleはindex.ctpに書くことが推奨されています。
<?php
$this->assign('title', 'blog Posts');
?>
パーツ
src->header->elementに書き込み、layoutに追記
<header>My Blog</header>
<body>
<?= $this->element('my_header'); ?>
<div class="container">
<?= $this->fetch('content') ?>
</div>
</body>
PostsController.phpはclass PostsController extends AppControllerと、AppControllerを継承しているので、AppControllerのpublic function initialize()に$this->viewBuilder()->layout(‘my_layout’);を書き込むこともあります。
リンクの張り方
HTMLヘルパー
<li><?= $this->Html->link($post->title, ['action'=>'view',$post->id]); ?></li>
URLヘルパー
<a href="<?= $this->Url->build(['action'=>'view', $post-id>]); ?>"> <?= h(post->title); ?> </a>