How To Install, Setup And Implement NodeJS In PHP Application

What Is NodeJS?

Typically in web response paradigm, the client always initiates communication, but with the help of NodeJS now both the client and server can initiate communication, allowing them to exchange data freely.

In simple words, after a database update the client needs to request the server to get the latest data. But using NodeJS, a client can send the updated data to NodeJS and the NodeJS will distribute the data across all the clients. So, no need to initiate request by each client to the server to get the latest data.

Where We Can Use NodeJS?

Below are the few examples where you can get the best out of Node.js,

  • A counter which updates after a record insert into database.
  • Show real-time activity like Twitter or Facebook.
  • Implement Desktop notification to notify users about what others are doing.
  • You can build a chatting tool using the non-blocking, event-driven I/O paradigm of NodeJS

Install And Setup NodeJS

  1. Install NodeJS and NPM
  2. Install socket.io using NPM
  3. Install Forever

Run the below notification.js file forever using the “Forever”. (it should not stop)

notification.js

var fs = require('fs');
/* If you are using SSL, uncomment the below lines*/
/*
var options = {
    key: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_key.key'),
    cert: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_crt.crt'),
    ca: fs.readFileSync('/var/www/html/YOUR_CERTIFICATE_FOLDER/your_project_ca-bundle.ca-bundle')
};
var app = require('https').createServer(options, handler);
*/

var app = require('http').createServer(handler); // For non-ssl server
var io = require('socket.io').listen(app);
app.listen(3002);
function handler (req, res) {
	res.writeHead(200);
	res.end("Welcome to socket.io.");
}
/** This section is for receiving and sending message **/
var Room;
io.sockets.on('connection', function (socket) {
	socket.on('subscribeTo', function (data) {
		if(Room){
			socket.leave(Room);
		}
		Room = data.channel;
		console.log('Connecting client to: '+data.channel);
		socket.join(data.channel);
	});
	socket.on('iotoserver', function (data) {
		console.log('here we are in action event and data is: \n-----------------------------------------------------');
		//var dataJSON = JSON.parse(data);
		//socket.broadcast.emit(dataJSON.channel, { message: 'A new socket added and sending message.' });
		socket.broadcast.to(data.channel).emit('iotoclient', { message: data.message });
		//io.sockets.in('game').emit('message', 'cool game');
		console.log(data);
	});
});

NOTE: Your Node.js should run with the port “3002”. Try to use another sub-domain/domain to call your Node.js server. Another server is always a good option.

Implement NodeJS In Your Application

Use Elephant.io (a socket.io client) to send message to NodeJS.
Get the ElephantIO package from, https://github.com/Wisembly/elephant.io/tree/master/src
You need the Client.php and the AbstractPayload.php file only.

<?php
use ElephantIO\Client as ElephantIOClient;
include("ElephantIO/Client.php");

$elephant = new ElephantIOClient('http://www.your-node-server.com:3002', 'socket.io', 1, false, false, true);
$elephant->setHandshakeTimeout(1000);
$elephant->init();
$elephant->send(
ElephantIOClient::TYPE_EVENT, null, null, json_encode(array('name' => 'iotoserver', 'args' => array('channel' => 'my_first_channel', 'message' => 'my message to all the online users')))
	);
$elephant->close();
?>

Put this JavaScript in the page, where you want to receive the real-time notification

<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script>
try{
  var client = io.connect('http://www.your-node-server.com:3002');
  
  client.on('connect',function (data) {
  	client.emit('subscribeTo', { channel: 'my_first_channel' });
  });
  
  client.on('iotoclient', function (data) {
    alert(data.message);
  });
} catch(e){
	console.log('Socket ERROR\n');
	console.log(e);
}
</script>

See Also: Creating a custom handler session in CakePHP 2.x

Are you looking to Install, setup and implement NodeJS in your PHP application? We are here to help you. We have experienced NodeJS developers to provide all types of JavaScript solutions. Let’s discuss

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

How To Access Remote Amazon RDS With PHPMyAdmin

Amazon Relational Database Service (Amazon RDS) is a web service that makes it easy to set up, operate, and scale a relational database in the cloud. It provides cost-efficient and resizable capacity while managing time-consuming database management tasks, freeing you up to focus on your applications and business.

First of all we need to install PHPMyAdmin in ec2 instance (CentOS, Fedora, Amazon Linux AMI)

Step:1

First we need to enable the RPMforge repository on our CentOS system as PHPMyAdmin is not available in the official CentOS/Fedora/Amazon Linux AMI repositories:

Import the RPMforge GPG key:

# rpm --import  http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt

On x86_64 systems:

#  yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

On i386 systems:

# yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm

Step:2

PHPMyAdmin can now be installed as follows:

# yum install phpmyadmin

Step:3

Now, we configure PHPMyAdmin. We change the Apache configuration so that PHPMyAdmin allows connections not just from localhost (by commenting out the <Directory “/usr/share/phpmyadmin”> stanza):

vi /etc/httpd/conf.d/phpmyadmin.conf
#
# Web application to manage MySQL
#
 
#<Directory "/usr/share/phpmyadmin">
# Order Deny, Allow
# Deny from all
# Allow from 127.0.0.1
#</Directory>
 
Alias /phpmyadmin /usr/share/phpmyadmin
Alias /phpMyAdmin /usr/share/phpmyadmin
Alias /mysqladmin /usr/share/phpmyadmin

Step:4

Next, we change the authentication in PHPMyAdmin from cookie to http: and host from local to RDS host url:

vi /usr/share/phpmyadmin/config.inc.php
[...]
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'http';
[...]
/* Server parameters */
$cfg['Servers'][$i]['host'] = '*******.******.us-east-1.rds.amazonaws.com';

Step:5

Restart Apache service:

# /etc/init.d/httpd restart

Step:6

Now we can browse RDS database.

# http://<IPADDRESS> /phpmyadmin

Or

# http://<Domain name>/phpmyadmin

Advantages Of PHPMyAdmin Over Command line Interface.

  • One of the advantages of using PHPMyAdmin is that it has a user interface and you can run queries within the SQL.
  • It is also used in checking referential integrity in MyISAM tables.
  • One can execute, edit and bookmark any SQL-statement, even batch-queries (This will work only in the latest version of PHPMyAdmin).
  • Multiple MySQL servers can be managed by PHPMyAdmin.
  • One can export data to various formats: CSV, SQL, XML, Excel and more.
  • Using Query-By-Example(QBE), create complex queries automatically connecting required tables.
  • One can Browse, view and drop databases, tables, views, fields and indexes.
  • It supports InnoDB tables and foreign keys.

Also See: How to install and configure Jaspersoft in Linux Server(RHEL/Centos/Fedora)

I hope you will find this useful. Feel free to give your valuable feedback.

If you want to update your traditional IT infrastructure to cloud computing, then you can hire expert cloud engineers from Andolasoft.

Utility Open Source Apps In CakePHP That You Need To Know

CakePHP is one of the most popular open source web application framework. It provides an extensible architecture for development, maintenance and deployment of PHP applications. Being based on the MVC Architecture & ORM, it is relatively simple to understand and helps developers to write less code without losing flexibility.

The key features of Open Source Apps written in CakePHP are:

  • Flexible Licensing
  • Works from any Website Directory, with Little Number of Apache Configuration involved
  • Integrated CRUD for Database Interaction
  • Code Generation & Built-in Validation
  • Request Dispatcher with Clean, Custom URLs and Routes
  • Fast and Flexible Templating (PHP Syntax with Helpers)
  • View Helpers for AJAX, JavaScript, HTML Forms and much more
  • Email, Cookie, Security, Session and Request Handling Components
  • Flexible ACL and Data Sanitization
  • Flexible Caching and Localization

CakePHP has the second largest active developer team and community among the PHP frameworks, bringing great value to the project. It keeps you away from reinventing the wheel.

Never miss an update from us. Join 10,000+ marketers and leaders.

Github is the #1 resource for Cakephp projects in my opinion. 2nd place probably is occupied by Code Google and then comes Sourceforge.

Orangescrum

Orangescrum is a flexible project management web application developed using CakePHP framework. It’s an efficient Project Collaboration Tool that gives you full visibility and control over your projects. Orangescrum offers all the basic features you need for smooth running of your project. No matter where you are globally, with Orangescrum you feel like sitting next to your developer. With an intuitive interfaces, easy-to-use functionality, you organize your project activities to a great extent.

Disclaimer: It’s our own project management tool.

https://github.com/Orangescrum/orangescrum

Croogo

Croogo is a free, open source, Multilingual Content management system built using CakePHP MVC framework. It’s an open source project released under MIT License. With Croogo CMS, you can create your own content type such as blog, node, page, etc.  Also you can categorize content with Taxonomy and it also offers WYSIWYG editor to edit content directly from browser.

Zhen CRM

Zhen CRM is a self-hosted CRM with full source code (in CakePHP and MySQL) that aims to be visually easy to use, simple and straightforward, and provides all the features you need from a full-featured CRM!

Vamcart

Vamcart is a CakePHP based open source Shopping cart. It is easy to use and simple to install. It is not required to have any special knowledge to install Vamcart on your server. Just download the files from vamcart homepage and put them on your server’s root directory and open Vamcart installation page directly from the browser. The script will automatically install shopping cart on your site.

QuickApps

QuickApps is a CakePHP based open source Content management system. It is easy to use and simple to install. It allows developers and advanced users to easily build complex websites without reinventing the wheel.

 

Recommended Blog: Containable Behavior in CakePHP

Definitely, this list is incomplete. Share your favorite open source CakePHP application with us in the comments below.

How To Do Custom Pagination In CakePHP

Sometimes we need to do pagination in CakePHP using a traditional SQL query, thereby the CakePHP predefined pagination functionality is lost.

We can implement pagination method in the Model or Behavior when we are using standard SQL query in CakePHP. Just need to make sure that the result cannot be obtained with core model methods, or a custom finder before implementing custom queries pagination.

But we can’t just use the standard pagination on the custom queries, we have to override the paginate functions in model or behavior.

To use our own method/logic to override the CakePHP pagination in the model, we need to add two functions: paginate() and paginateCount().

In these functions, we can implement our own paginate logic.

Overriding paginate() function in CakePHP Post Model:

[php]public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$orderStr = ”;
foreach($order as $k =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; $ord) {
$orderStr[] = $k . ‘ ‘ . $ord;
}
$orderStr = ‘ORDER BY ‘. implode(‘, ‘, $orderStr);

$qryCond = ‘1’;
if (isset($conditions[‘Post.title LIKE’])) {
$qryCond = ‘title LIKE \”.$conditions[‘Post.title LIKE’].’\”;
}

$qryFlds = ‘*’;
if ($fields) {
$qryFlds = implode(‘, ‘, $fields);
}

$sql = ‘SELECT ‘.$qryFlds.’ FROM posts as Post WHERE ‘.$qryCond.’ ‘.$orderStr . ‘ LIMIT ‘ . (($page-1) * $limit) . ‘, ‘ . $limit;
$results = $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;query($sql);
return $results;
}[/php]

Overriding paginateCount() function in CakePHP Post Model:

[php]public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$qryCond = ‘1’;
if (isset($conditions[‘Post.title LIKE’])) {
$qryCond = ‘title LIKE \”.$conditions[‘Post.title LIKE’].’\”;
}

$sql = ‘SELECT COUNT(*) as count FROM posts as Post WHERE ‘.$qryCond;

$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;recursive = -1;

$results = $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;query($sql);
return $results[0][0][‘count’];
}[/php]

Using in the Post Controller: We can adjust the fields to get, column ordering, add certain conditions or adjust row limit per page.

[php]public function index() {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;paginate = array(
‘limit’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; 10,
‘fields’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.id’, ‘Post.title’, ‘Post.created’),
‘conditions’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.title LIKE’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘%search_keyword%’),
‘order’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; array(‘Post.title’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘asc’, ‘Post.id’ =&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; ‘asc’)
);
try {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;set(‘posts’, $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;paginate(‘Post’));
} catch (NotFoundException $e) {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;redirect(‘index_custom’);
}
}[/php]

The above example is based on specific model and requirement, need to adjust the methods according to the requirements.

See Also: Creating a custom handler session in CakePHP 2.x

Best of luck and happy pagination.

Hope you liked this. Let me know if you want to add anything?

How To Setup CakePHP DataSource For Solr?

Imagine that you have millions of data and your SQL database is not optimized enough to handle them, then “Solr” is your best data source. Apache Solr is a fast search platform. It’s major features include full-text search faceted search, dynamic clustering, database integration, rich document handling. Solr is highly scalable and it is the most popular enterprise search engine.

This document will guide you through DataSource setup for Solr in CakePHP. Set-up the Solr DataSource in CakePHP and query Solr with your CakePHP model “find” function, just similar to querying any other SQL database.

/app/Config/database.php:

Configuring your the DataSource for Solr database connection:

  • host: Solr server address.
  • port: Solr server port.
  • datasource: This should match with your DataSource at /app/Model/Datasource/SolrSource.php

[php]class DATABASE_CONFIG {
public $solr = array(
‘datasource’ =&amp;amp;amp;gt; ‘SolrSource’,
‘host’ =&amp;amp;amp;gt; ‘192.168.2.131’,
‘port’ =&amp;amp;amp;gt; ‘9983’,
‘path’ =&amp;amp;amp;gt; ‘/solr/’
);
}[/php]

/app/Model/Solr.php:

Use the database config in your models like:

[php]class Solr extends AppModel {
 public $useTable = false;
 public $useDbConfig = ‘solr’;
 }[/php]

/app/Model/Datasource/SolrSource.php:

Below code describes only the most required functions.

  • You can find other required functions at http://book.cakephp.org/2.0/en/models/datasources.html
    Like: calculate($model, $func, $params) and others create(), update(), delete().
  • Below DataSource only implements read() function.
  • Create a file called SolrSource.php and use below code:

[php]App::uses(‘HttpSocket’, ‘Network/Http’);
require_once($_SERVER[‘DOCUMENT_ROOT’].’/root_folder/app/Vendor/Apache/Solr/Service.php’);
class SolrSource extends DataSource {

protected $_schema = array();
protected $_host;
protected $_port;

public function __construct($config){
parent::__construct($config);
$this-&amp;amp;amp;gt;Http = new HttpSocket();

$this-&amp;amp;amp;gt;host = $config[‘host’];
$this-&amp;amp;amp;gt;port = $config[‘port’];
$this-&amp;amp;amp;gt;_schema = $config[‘path’];

$this-&amp;amp;amp;gt;solr=new Apache_Solr_Service($this-&amp;amp;amp;gt;host, $this-&amp;amp;amp;gt;port, $this-&amp;amp;amp;gt;_schema);
}

public function read(Model $model, $queryData = array(), $recursive = null) {
$results = array();
$query = $queryData[‘conditions’][‘solr_query’];
if (Configure::read(‘log_solr_queries’) === true) {
CakeLog::write(‘debug’, $query); /* Logs the solr query in app/tmp/logs/debug.log file */
}

try {
$solr_docs = $this-&amp;amp;amp;gt;solr-&amp;amp;amp;gt;search($query, $queryData[‘offset’], $queryData[‘limit’], array(‘sort’ =&amp;amp;amp;gt; $queryData[‘order’]));
} catch (Exception $e) {
CakeLog::write(‘error’, $e-&amp;amp;amp;gt;getMessage()); /* Logs the solr errors message in app/tmp/logs/error.log file */
CakeLog::write(‘error’, $query); /* Logs the solr query in app/tmp/logs/error.log file */
}
$model-&amp;amp;amp;gt;params = $solr_docs-&amp;amp;amp;gt;responseHeader-&amp;amp;amp;gt;params;
$model-&amp;amp;amp;gt;numFound = $solr_docs-&amp;amp;amp;gt;response-&amp;amp;amp;gt;numFound;
$docs = $solr_docs-&amp;amp;amp;gt;response-&amp;amp;amp;gt;docs;
foreach ($docs as $doc) {
$document = array();
foreach ($doc as $fieldName =&amp;amp;amp;gt; $fieldValue) {
$document[$fieldName] = $fieldValue;
}
$results[] = $document;
}
return array($model-&amp;amp;amp;gt;alias =&amp;amp;amp;gt; $results);
}
}[/php]

/app/Controller/UsersController.php:

Getting data from Solr server by using above SolrSource.

[php]App::uses(‘AppController’, ‘Controller’);
class UsersController extends AppController {

public $name = ‘Users’; //Controller name
public $uses = array(‘Solr’); //Model name

function beforeFilter(){
parent::beforeFilter();
$this-&amp;amp;amp;gt;Auth-&amp;amp;amp;gt;allow(‘index’);
}

public function index(){
$cond = "active:1";
$sort = "timestamp desc";

$params = array(
‘conditions’ =&amp;amp;amp;gt;array(
‘solr_query’ =&amp;amp;amp;gt; $cond
),
‘order’ =&amp;amp;amp;gt; $sort,
‘offset’ =&amp;amp;amp;gt; 0,
‘limit’ =&amp;amp;amp;gt; 1
);

$result = $this-&amp;amp;amp;gt;Solr-&amp;amp;amp;gt;find(‘all’, $params);
$this-&amp;amp;amp;gt;layout = ‘ajax’;
header(‘Content-Type: application/json; charset=utf-8’); /* To send response in json format */
echo json_encode($result);
die;
}
}[/php]

See Also : How to use ‘neighbors’ with ‘find’ method

Debugging:

The above code has been tested and validated with CakePHP 2.2.3, PHP 5.3.1 .
Incase you face any problems:

  • First check the DataSource configuration in /app/Config/database.php.
  • Check /app/Model/Solr.php for this line: public $useDbConfig = ‘solr’;
  • Make sure Solr Service Vendor loaded in /app/Model/Datasource/SolrSource.php.
  • Check the path is correct for the Solr vendor.

Hope you liked this. Let me know if you want to add anything?

Creating A Custom Handler Session In CakePHP 2.x

Sessions manage and customization is very easy in CakePHP. Setting and configuration come out of the box so basically you don’t need to configure at all. But still at some point we need customization like, if we need some changes in php.ini or want to store session in a different place.

You can manage session, write custom handler, add option to save on different places, override php.ini settings.

Write Your Own Custom Handler For Sessions in Cake:

To Save Session With Setting in php.ini:

Configure::write('Session', array(
'defaults' => 'php'
));

This is the default setting that comes out of the box by CakePHP.

To Save Session Inside Cake tmp Folder:

Configure::write('Session', array(
'defaults' => 'cake'
));

This is required in a host where it does not allow you to write outside your home directory.

To Save Session in Database:

Configure::write('Session', array(
'defaults' => 'database'
));

This uses a built-in database defaults. It stores session in ‘cake_sessions’ table.
So you need to create a table for this:

CREATE TABLE `cake_sessions` (
`id` varchar(255) NOT NULL DEFAULT '',
`data` text,
`expires` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);

But you can specify you own session handler to store session using a different model:

Configure::write('Session', array(
'defaults' => 'database',
'handler' => array(
'model' => 'MyCakeSession'
)
));

Create ‘MyCakeSession’ model at app/Model/MyCakeSession.php  And create ‘my_cake_sessions’ table:

CREATE TABLE `my_cake_sessions` (
`id` varchar(255) NOT NULL DEFAULT '',
`data` text,
`expires` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);

This will save session ‘my_cake_sessions’ using MyCakeSession model.

To Save Session in Cake Cache:

Configure::write('Session', array(
'defaults' => 'database'
));

Making Session Persist Across All Sub-Domains:

  • Add below in bootstrap:
    ini_set(‘session.cookie_domain’, env(‘HTTP_BASE’));
  • This changes the default, that only the domain generating a session can access, to all sub-domains.
  • You don’t need to make core Security.level to low or medium.
  • You can also use php, cake, database or cache in core Session default to persist session in all sub-domains.

Troubleshoot:

  • When you test with the session management you might get error: “cakephp 404 The request has been black-holed”.
  • Try clear tmp/cache/, tmp/cache/models, tmp/cache/persistent, tmp/sessions.
  • Try clear browser cookie and cache.
  • Check core Session configurations.

Always try to clear browser cookie, cache before doing changes in core Session or php.ini configuration.

Other Session configuration that can be done are cookie name, timeout, cookieTimeout, checkAgent, autoRegenerate, and other ini values like cookie_secure, cookie_path, cookie_httponly.

See Also : How to migrate CakePHP 1.x to 2.x

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.