cakePHP-ブログチュートリアル 2日目
/app/ModelにPosts.phpを追加。
class Post extends AppModel { }
/app/ControllersにPostsController.phpを追加。
class PostsController extends AppController { public $helpers = array('Html', 'Form'); public function index() { $this->set('posts', $this->Post->find('all')); } }
/app/Views/Postsにindex.ctpを追加
<h1>Blog posts</h1> <table> <tr> <th>Id</th> <th>Title</th> <th>Created</th> </tr> <?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>
ここで
http://localhost:8888/cakephp/Posts/indexで表示を確認してみると、
日本語の部分が文字化けしてしまう。
/Config/database.phpの前回編集した部分の一番下に
//'encoding' => 'utf8',
とあるので、
'encoding' => 'utf8',
このように'//'を消してコメントアウトを解除して有効にしたら解決した。
/app/Controllers/PostsController.phpに以下を追加。
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/Views/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>
ここまででデータベースから記事を引っ張ってきて見ることができるようになった。
記事一覧は
http://localhost:8888/cakephp/Posts/index
記事を見るには記事一覧のリンクから飛ぶか
http://localhost:8888/cakephp/posts/view/1 (末尾の数字は記事のid)
にアクセスする。
とりあえずここまで。