Yii2: Tutorial Membuat Blog Sederhana Part I

Tutorial ini merupakan lanjutan dari artikel Yii2 sebelumnya, Asumsi Anda telah mengikuti tutorial sebelumnya,

Oke setelah aplikasi Yii2 ready,maka untuk mengeksplore pemahaman kita, berikut ini saya bawakan study kasus yaitu membuat web blog sederhana.. mengapa sederhana? ya agar saya tidak terlalu panjang nulisnya (padahal karena saya nyubi).. silahkan di kembangkan sendiri :)

Pada tutorial ini, aplikasi web blog dibagai menjadi 2 yaitu frontend untuk pengunjung baca artikel dan backend untuk admin bikin artikel.. Hem.. artikel ini akan saya buat bertahap..

Pada bagian pertama ini saya akan fokus ngoprek FRONTENDnya

1) Modify Layout

  • buka file frontend\views\layouts\main.php, lalu modifikasi

- Brand Url (line 29)

'brandLabel' => 'My Blog',

- Footer Text (line 68)

<p class="pull-left">&amp;copy; My Blog <?= date('Y') ?></p>

 

  • buka file frontend\views\views\site\index.php, , lalu modifikasi

- drop class jumbotron & edit text

<div>
 <h1>Yii Tutorials!</h1>
<p class="lead">Let's Fun Learn Yii Framework Version 2.0.</p>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Are You Ready?</a></p>
 </div>

- Buat layout dengan 2 column (9 vs 3) main (list articles) and sidebar (menus)

<div class="row">
	<div class="col-lg-9">
		<div>
			<h2>Judul</h2>
			<p>Content</p>
		 </div>
	</div>
	<div class="col-lg-3">
		<h2>Category</h2>
	</div>
</div>

Referensi:

http://getbootstrap.com/css

http://getbootstrap.com/examples/blog/

- untuk sidebar menu yang berisi category gunakan widget Nav bootstrap untuk membuat tampilan menu

use yii\bootstrap\Nav;
echo Nav::widget([
	'items' => [
		['label'=>'category 1','url'=>'#'],
		['label'=>'category 2','url'=>'#'],
	],
]);

agar rapi use Nav nya bisa anda letakkan bagian atas dari file ini.

2) Adjust Structure Database

Structure databasenya kira2 begini.. ada 3 tabel jadi total 4 tabel dengan tabel user yang udah tercipta saat migrate

CREATE TABLE category
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
create_time INTEGER,
update_time INTEGER
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE post
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(128) NOT NULL,
content TEXT NOT NULL,
category_id INTEGER NOT NULL,
status INTEGER NOT NULL,
create_time INTEGER,
update_time INTEGER,
user_id INTEGER NOT NULL,
CONSTRAINT FK_post_category FOREIGN KEY (category_id)
REFERENCES category (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_post_user FOREIGN KEY (user_id)
REFERENCES user (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE comment
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
content TEXT NOT NULL,
status INTEGER NOT NULL,
create_time INTEGER,
author VARCHAR(128) NOT NULL,
email VARCHAR(128) NOT NULL,
url VARCHAR(128),
post_id INTEGER NOT NULL,
CONSTRAINT FK_comment_post FOREIGN KEY (post_id)
REFERENCES post (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO category (name) VALUES('Uncategory');

INSERT INTO post (title, content, status, create_time, update_time, user_id, category_id) VALUES ('Welcome!','This blog system is developed using Yii. It is meant to demonstrate how to use Yii to build a complete real-world application. Complete source code may be found in the Yii releases.
Feel free to try this system by writing new posts and posting comments.',1,1230952187,1230952187,1,1);
INSERT INTO post (title, content, status, create_time, update_time, user_id, category_id) VALUES ('A Test Post', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 1,1230952187,1230952187,1,1);
INSERT INTO comment (content, status, create_time, author, email, post_id) VALUES ('This is a test comment.', 1, 1230952187, 'Tester', 'tester@example.com', 1);
Ini file sql generate 3 tabel

https://drive.google.com/file/d/0BwSv7MUYD04kWmVNeEktTE45NlU/edit?usp=sharing

3) Create Model via Gii

http://back.end/gii

Buat CRUD Model untuk semua tabel dan jangan lupa gunakan Namespace common\models, yap karena model ini akan digunakan di semua aplikasi (front dan backend)

4). Update Site Controller Part I (Provide data to show in view)

buka file frontend\controllers\siteController.php, lalu modifikasi

public function actionIndex()
 {
 $posts = \common\models\Post::find()
 ->where(['status' => 1])
 ->orderBy('id DESC')
 ->limit(3)
 ->all();
$categories = \common\models\Category::find()
 ->orderBy('name ASC')
 ->all();
return $this->render('index', [
 'posts' => $posts,
 'categories' => $categories,
 ]);
 }

5) Show Data to View Fronted

buka file frontend\views\site\index.php, lalu modifikasi

  • Post
<?php
foreach($posts as $post){
echo '<div>';
echo '<h2>'.$post->title.'</h2>';
echo '<p>'.substr($post->content,0,300).'...</p>';
echo '<p><small>Posted by '.$post->user->username.' at '.date('F j, Y, g:i a',$post->create_time).'</small></p>';
echo '<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">readmore &amp;raquo;</a></p>';
echo '</div>';
}
?>

link readmore havenot defined

  • Category

Category

<?php
$items=[];
foreach($categories as $category){
$items[]=['label' => $category->name , 'url' => '#'];
}
echo Nav::widget([
'items' => $items,
]);
?>

link category havenot defined

6). Update Site Controller Part II (Create action Category Post & Single Post)

- Category Post

public function actionPostCategory($id)
{
$posts = \common\models\Post::find()
->where(['status' => 1, 'category_id' => $id])
->orderBy('id DESC')
->limit(5)
->all();
<p>$categories = \common\models\Category::find()
->orderBy('name ASC')
->all();
<p>return $this->render('postCategory', [
'posts' => $posts,
'categories' => $categories,
]);
}

- create file postCategory.php di folder frontend\views\site\
postCategory.php same with file index.php
- Try http://front.end/site/post-category?id=1
- edit link category in sidebar index.php and postCategory.php

- Single Post

public function actionPostSingle($id)
{
$post = \common\models\Post::find()
->where(['status' => 1, 'id' => $id])
->one();
<p>$categories = \common\models\Category::find()
->orderBy('name ASC')
->all();
<p>return $this->render('postSingle', [
'post' => $post,
'categories' => $categories,
]);
}

- create file postSingle.php di folder frontend\views\site\
postSingle.php identic with file index.php but for single category
- Try http://front.end/site/post-single?id=1
- edit link readmore in main index.php and postCategory.php

signup

Jika ketinggalan (emang kereta) ini file aslinya..

https://drive.google.com/file/d/0BwSv7MUYD04kTm1OSy1TR2xjZjg/edit?usp=sharing

Sementara done dulu lanjut kapan2.. :)

Tags:
19 Comments
  1. Audi Roly
  2. Audi Roly
    • Hafid Mukhlasin
  3. Kuro
    • Hafid Mukhlasin
  4. andri
    • Hafid Mukhlasin
  5. imron
  6. charlie
  7. ahmad
    • keram-otak
  8. Ridwan Hidayat
  9. ogi
  10. man
  11. vendi
  12. Arno
  13. dendy

Leave a Reply

Your email address will not be published. Required fields are marked *