Thứ Năm, 24 tháng 4, 2014

Building a simple group chat [Chat and E-mail]

Our nextask is to build a simple group chat application that allows multiple userto log in to our system and chat with each other. The backend for this tool is pretty straightforward. We need to create a table that will store all user messages and render them in a separate view; we will create a simple form that will allow userto send messages.
1.       Create a nechat_messages table tstore all user messages:
CREATE TABLE IF NOT EXISTS chat_messages (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , user_id INT NOT NULL,
message VARCHAR( 255 ) NOT NULL ,
stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)


2.       Create a controller for group chat in CommunicationApp/module/Users/src/ Users/Controller/GroupChatController.php.
3.       Make necessary changes tCommunicationApp/module/Users/config/ module.config.php and add the necontroller to invokables and routes:
// Invokable
'Users\Controller\GroupChat' => 'Users\Controller\ GroupChatController',

// Route
'group-chat' => array( 'type' => 'Segment', 'options' => array(
'route'    => '/group-chat[/:action[/:id]]', 'constraints' => array(
'action'     => '[a-zA-Z][a-zA-Z0-9_-]*', 'id'     => '[a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Users\Controller\GroupChat', 'action'    => 'index',
),
),
),

4.       Create a new view in CommunicationApp/module/Users/view/users/group- chat/index.phtml:
<?php
$this->headScript()->appendScript( '$(function() {
$( "#btnRefresh" )
.click(function( event ) { document.getElementById("messageListFrame").contentWindow.
location.reload(true);
})
});', 'text/javascript');

$this->headStyle()->appendStyle('
#userName { width:100px; margin-top:10px; display: inline}
#messageText { width:700px; margin-top:10px;} ');
?>
<h3>Group Chat</h3>
<iframe src="<?php echo $this->url('users/group-chat', array(


'action' =>  'messageList'
)) ?>" width="80%" height="400px" id="messageListFrame"></iframe>

<?php
// Render the opening tag
echo $this->form()->openTag($form);

// ...loop through and render the form elements...
echo '<label id="userName">'. $userName .': </label>'; foreach ($form as $element) {
echo $this->formElement($element);        // <-- Magic!
echo $this->formElementErrors($element);
}

// Render the closing tag
echo $this->form()->closeTag();
?>

5.       Add the messageList action tGroupChatController - CommunicationApp/module/Users/src/Users/Controller/ GroupChatController.php; this action will query thechat_messages table and get all the records from thatable and pass that on to the view:
public function messageListAction()
{
$userTable = $this->getServiceLocator()->get('UserTable');
$chatMessageTG = $this->getServiceLocator()->get('ChatMessagesTa bleGateway');
$chatMessages = $chatMessageTG->select();

$messageList = array(); foreach($chatMessages as $chatMessage) {
$fromUser = $userTable->getUser($chatMessage->user_id);
$messageData = array();
$messageData['user'] = $fromUser->name;
$messageData['time'] = $chatMessage->stamp;
$messageData['data'] = $chatMessage->message;
$messageList[] = $messageData;
}

$viewModel  = new ViewModel(array('messageList' =>
$messageList));
$viewModel->setTemplate('users/group-chat/message-list');
$viewModel->setTerminal(true); return $viewModel;
}


6.       Create a simple message listing viewCommunicationApp/module/Users/view/ users/group-chat/message-list.phtml, which will list messages from the
$messageList array:
<!DOCTYPE html>
<html lang="en">
<body>
<section id="messages" >
<?php foreach ($messageList as $mesg) : ?>
<div class="message" style="clear:both;">
<span class='msg-time'>
[<?php echo $this->escapeHtml($mesg['time']);?>]
</span>
<span class='msg-user'>
<?php echo $this->escapeHtml($mesg['user']);?>:
</span>
<span class='msg-data'>
<?php echo $this->escapeHtml($mesg['data']);?>
</span>
</div>
<?php endforeach; ?>
</section>
</body>
</html>

7.       Create a method called sendMessage(), which is called when a user sends a messagtstore the message in the database, as shown in the following code.
This needs to be placed in the group chacontroller CommunicationApp/module/ Users/src/Users/Controller/GroupChatController.php.
protected function sendMessage($messageTest $fromUserId)
{
$chatMessageTG = $this->getServiceLocator()
->get('ChatMessagesTableGateway');
$data = array(
'user_id' => $fromUserId, 'message'     => $messageTest, 'stamp' => NULL
);
$chatMessageTG->insert($data); return true;
}


8.       Modify the indexAction function to display Send Message form and tcall sendMessage() on form submission. This needs to be placed in the group chacontrollerCommunicationApp/module/Users/src/Users/Controller/ GroupChatController.php.
public function indexAction(
{
$user = $this->getLoggedInUser();
$request = $this->getRequest(); if ($request->isPost()) {
$messageTest = $request->getPost()->get('message');
$fromUserId = $user->id;
$this->sendMessage($messageTest, $fromUserId);
// to prevent duplicate entries on refresh
return $this->redirect()->toRoute('users/group-chat');
}

//Prepare Send Message Form
$form    = new \Zend\Form\Form();

$form->add(array( 'name' => 'message', 'attributes' => array(
'type'  => 'text',
'id' => 'messageText', 'required' => 'required'
),
'options' => array( 'label' => 'Message',
),
));

$form->add(array(
'name' => 'submit', 'attributes' => array(
'type'  => 'submit',
'value' => 'Send'
),
));

$form->add(array( 'name' => 'refresh', 'attributes' => array(
'type'  => 'button', 'id' => 'btnRefresh',


'value' => 'Refresh'
),
));

$viewModel  = new ViewModel(array('form' => $form, 'userName' => $user->name));
return $viewModel;
}

9.       To test the changes, log in to the browser from two different computers or two different browsers using different credentials, and test the Group Chat interface.


What just happened?
We have now successfully implemented a Group Chat interface using Zend Framework; the interface is effective for multiple people chatting with each other in a group. Our nextask will need to build a mechanism to send e-mails to other users in the system; for thawe will be exhaustively using the Zend Framework's mailing capabilities.
Here is a simple exercise for you to try beforyou move on to the next section. In the Group Chat interface, we have a Refresh button thareloads the iframe tag. Write some JavaScript and attach it to the view, which willreload the IFrame every five seconds.

Không có nhận xét nào:

Đăng nhận xét