July 15, 2013
by Sabit Huraira
Melanjutkan previous post di https://sabitlabscode.wordpress.com/2013/07/14/php-yii-mongodb-work-with-data-relation/, postingan ini akan membahas penggunaan cara ke 2 yaitu dengan cara memasukkan langsung data ke dalam document. Anggaplah saya memiliki document “news” yang data nya terdiri dari :
news : title, news, comments [comment_title, comment_name, comment]
dapat anda lihat bahwa setiap satu “news” dapat memiliki banyak komentar di dalamnya. Bagaimana cara membuatnya? Okeh, pertama-tama kita buat terlebih dahulu modelnya, kita definisikan semua fungsi-fungsi yang kita butuhkan mulai dari savedate, edit, delete, findall, findone, da addcomment. Sehingga model anda akan menjadi seperti berikut :
<?php
//definition model name
class NewsForm extends CFormModel
{
//define variable in model
public $title;
public $news;
public $comment_name;
public $comment_title;
public $comment;
// rule validation
public function rules()
{
return array(
array('title,news', 'required'),
//required just when we add comment
array('comment_name,comment_title,comment','required','on'=>'createcomment'),
);
}
//attribute label in form
public function attributeLabels()
{
return array(
'title'=>'Title',
'news'=>'Insert Your News Here',
'comment_name'=>'Created By',
'comment_title'=>'Comment Title',
'comment'=>'Comment',
);
}
//run it for save data
public function savenews()
{
try {
//get connection to access document
$connection = new Mongo();
$collection = $connection->belajar->news;
$varnews = array(
'title' => $this->title,
'news' => $this->news,
);
//insert data
$collection->insert($varnews,array('safe'=>true));
return true;
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die('Failed to insert data '.$e->getMessage());
}
}
//run it for update data
public function editnews($id)
{
try {
$connection = new Mongo();
$collection = $connection->belajar->news;
$varnews = array('$set'=>array(
'title' => $this->title,
'news' => $this->news,
)
);
//update data
$collection->update(array('_id' => new MongoId($id)),$varnews);
return true;
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die('Failed to insert data '.$e->getMessage());
}
}
//run it for delete data
public function deletenews($id)
{
try {
$connection = new Mongo();
$collection = $connection->belajar->news;
//remove data
$collection->remove(array('_id'=>new MongoId($id)));
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die('Failed to do operation '.$e->getMessage());
}
}
// this will return all data from document nilai
public function findallmongo()
{
try {
$connection = new Mongo();
$collection = $connection->belajar->news;
//get all data
$result= $collection->find();
return $result;
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die($e->getMessage());
}
}
// find news by id
public function findOneById($id)
{
try
{
$connection = new Mongo();
$collection = $connection->belajar->news;
//get data by $id in parameter
return $collection->findOne(array('_id'=>new MongoId($id)));
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die($e->getMessage());
}
}
//use for add a comment in news
public function addcomment($id)
{
try
{
$connection = new Mongo();
$collection = $connection->belajar->news;
//set some value for comment
$varcomment = array(
'comment_name' => $this->comment_name,
'comment_title' => $this->comment_title,
'comment'=>$this->comment
);
// we use $push to add insert value to comments
// if we not use $push, it replace old data that
// we have insert
$collection->update(array('_id' => new MongoId($id)),
array('$push' =>array('comments' => $varcomment)),
array('upsert'=>true));
}
catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
catch(MongoException $e) {
die($e->getMessage());
}
}
}
Setelah membuat model, kita lanjutkan dengan membuat controller agar user dapat melakukan request pada action-action yang telah kita tentukan. Pada controller ini kita akan menyediakan action-action berikut :
– action index = view all data from news
– actionview = show single data by id, pada actionview juga akan disediakan fitur untuk menambah komentar
– actioncreate = insert new data to document
– actionupdate = update data
– actiondelete = delete data from document
dan berikut adalah code dari controller nya :
<?php
class NewsController extends Controller
{
// action index to see all data in document nilai
public function actionIndex()
{
$model=new NewsForm;
//get all data from model
$data=$model->findallmongo();
$this->render('index',array(
'data'=>$data,
'model'=>$model,
));
}
// it will show detail data from tabel "nilia"
public function actionView($id)
{
$model=new NewsForm('createcomment');//it will do validation for "createdcomment"
// call a data from model "news" by id
$data=$model->findOneById($id);
//set field model with $data that
//we get from model
$model->news=$data['news'];
$model->title=$data['title'];
//if user do submit(POST) data
//for write a comment, then do this
if(isset($_POST['NewsForm']))
{
//set value with data that have been submitted
$model->comment_name=$_POST['NewsForm']['comment_name'];
$model->comment_title=$_POST['NewsForm']['comment_title'];
$model->comment=$_POST['NewsForm']['comment'];
//check validate
if($model->validate())
{
// call function addcomment
if($model->addcomment($id))
{
$this->redirect(array('view'));
}
}
}
$this->render('view',array(
'data'=>$data,
'model'=>$model,
));
}
// it use for create new data
public function actionCreate()
{
$model=new NewsForm;
//when user do submit to this
if(isset($_POST['NewsForm']))
{
$model->news=$_POST['NewsForm']['news'];
$model->title=$_POST['NewsForm']['title'];
if($model->validate())
{
//save data
if($model->savenews())
{
$this->redirect(array('index'));
}
}
}
$this->render('update',array('model'=>$model));
}
// update data
public function actionUpdate($id)
{
//define model
$model=new NewsForm;
// get data by id
$data=$model->findOneById($id);
//set value
$model->news=$data['news'];
$model->title=$data['title'];
//do this when submit
if(isset($_POST['NewsForm']))
{
//set value with submit value
$model->news=$_POST['NewsForm']['news'];
$model->title=$_POST['NewsForm']['title'];
if($model->validate())
{
//edit data
if($model->editnews($id))
{
$this->redirect(array('index'));
}
}
}
$this->render('update',array('model'=>$model));
}
// delete data
public function actionDelete($id)
{
$model= new NewsForm;
$model->deletenews($id);
$this->redirect(array('index'));
}
}
Di atas adalah code controller kita. Anda dapat melihat pada komentar-komentar code nya untuk melihat penjelasannya.
Setelah membuat controller nya, sekarang saatnya membuat tampilan dari controller itu sendiri. Berikut tampilan yang akan kita buat mulai dari index.php
<h1>This Is All News That We Have In Mongodb</h1>
<?php echo CHtml::link('Create News',array('create')); ?>
<?php
while ($data->hasNext()):
$news= $data->getNext();
?>
<h2>
<?php echo CHtml::link($news['title'],array('view','id'=>$news['_id'])); ?>
</h2>
[[
<?php
$totalcomment=0;
if(isset($news['comments']))
$totalcomment=count($news['comments']);
echo 'Total Comment('.$totalcomment.') | ';
?>
<?php echo CHtml::link('Update',array('update','id'=>$news['_id'])) ?> |
<?php echo CHtml::link('Delete',array('delete','id'=>$news['_id'])) ?>
]]<br/>
<?php endwhile; ?>
Kemudian tampilan untuk actionCreate dan actionUpdate yaitu create.php
<h1>Test Mongo - Pelajaran</h1>
<div>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p>Fields with <span>*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div>
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title'); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div>
<?php echo $form->labelEx($model,'news'); ?>
<?php echo $form->textArea($model,'news'); ?>
<?php echo $form->error($model,'news'); ?>
</div>
<div>
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
dan yang terakhir adalah actionView yang akan menampilkan single data dan dapat menambahkan komentar di dalamnya :
<h1>View News</h1>
<h2><?php echo $data['title']; ?></h2>
<p><?php echo $data['news'];?></p>
<table>
<tr>
<td>Craeted By</td>
<td>Comment Title</td>
<td>Comment</td>
<?php
if(isset($data['comments']))
{
foreach ($data['comments'] as $key => $value) {
echo '<tr>';
echo '<td>'.$value['comment_name'].'</td>';
echo '<td>'.$value['comment_title'].'</td>';
echo '<td>'.$value['comment'].'</td>';
}
}
?>
</table>
<h2>Insert Your Comment Here :</h2>
<div>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p>Fields with <span>*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div>
<?php echo $form->labelEx($model,'comment_name'); ?>
<?php echo $form->textField($model,'comment_name'); ?>
<?php echo $form->error($model,'comment_name'); ?>
</div>
<div>
<?php echo $form->labelEx($model,'comment_title'); ?>
<?php echo $form->textField($model,'comment_title'); ?>
<?php echo $form->error($model,'comment_title'); ?>
</div>
<div>
<?php echo $form->labelEx($model,'comment'); ?>
<?php echo $form->textArea($model,'comment'); ?>
<?php echo $form->error($model,'comment'); ?>
</div>
<div>
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
Okeh, itulah dia sedikit contoh membuat proses CRUD untuk document mongodb yang memiliki embedded document di dalamnya. Yang perlu diperhatikan adalah kapan kita harus menggunakan relasi langsung dan kapan kita menggunakan embed document karena tentu ini akan berpengaruh pada aplikasi yang anda buat..
Finish… Hope it help.. Happy coding… 😀
Komentar