I would prefer to not have a separate script merely to call command line execution.
testNotification.php
<?php
include_once 'Notification.php';
use Bubba\Util\Notification;
$Notification = new Notification();
$Notification->sendNotification('some1token', 33);
This assumes our Notification class file is in the same directory, although it is expected it would be in a library directory that is not web accessible.
Notification.php
<?php
namespace Bubba\Util;
if (Notification::isCommandLineInterface()){
$shortopts = "";
$shortopts .= "t:"; // The Token, Required value
$shortopts .= "c:"; // The Count, Required value
$options = getopt($shortopts);
$Notification = new Notification();
$Notification->sendNotification($options['t'], $options['c']);
exit;
}
class Notification {
protected $_token;
protected $_count;
public function __construct() {
}
public function sendNotification($token = NULL, $count = NULL){
$this->setCount($count);
$this->setToken($token);
// If we are running from the command line
// then we just want to send the notification
if ($this->isCommandLineInterface()){
print "I am notifying you with [{$this->_token}] that the count is [{$this->_count}]\n";
}else{
$cmd = '/usr/bin/php ' . __FILE__ . " -t='{$this->_token}' -c={$this->_count} >> notification.log 2>&1 &";
exec($cmd );
}
}
/**
* Do some appropo validation, you don't want stuff injected
* @param string $token
*/
protected function validateToken($token){
if (empty($token) || !is_string($token)){
$this->_token = NULL;
}
}
/**
* Do some appropo validation, you don't want stuff injected
* @param string $token
*/
protected function validateCount($count){
if (empty($count) || !is_numeric($count)){
$this->_count = 0;
}
}
/**
* Determine if this is running on the command line or not.
* @return boolean
*/
public static function isCommandLineInterface(){
return (php_sapi_name() === 'cli');
}
/**
* @return the $_token
*/
public function getToken() {
return $this->_token;
}
/**
* @return the $_count
*/
public function getCount() {
return $this->_count;
}
/**
* @param NULL $_token
*/
public function setToken($_token) {
$this->validateToken($_token);
$this->_token = $_token;
}
/**
* @param number $_count
*/
public function setCount($_count) {
$this->validateCount($_count);
$this->_count = $_count;
}
}
In this case, you can merely browse to http://your.localhost.net/testNotification.php and testNotification will instantiate the Notification object, and call the notify function. The notify function will realize it is not a CLI call, so it will make the exec call and return immediately. The exec call will load the Notifcation.php file, and realize that it is running from the CLI, thus it will instantiate itself, grab appropriate command line options, send the notification, and exit.
You can verify that by noticing a new notification.log in the same directory with the appropriate notification message.