コマンドライン実行を呼び出すためだけに別のスクリプトを用意したくありません。
testNotification.php
<?php
include_once 'Notification.php';
use Bubba\Util\Notification;
$Notification = new Notification();
$Notification->sendNotification('some1token', 33);
これは、Notification クラス ファイルが同じディレクトリにあることを前提としていますが、Web アクセスできないライブラリ ディレクトリにあることが予想されます。
通知.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;
}
}
この場合、http://your.localhost.net/testNotification.php を参照するだけで、 testNotification が Notification オブジェクトをインスタンス化し、notify 関数を呼び出します。通知機能は、それが CLI 呼び出しではないことを認識するため、exec 呼び出しを行い、すぐに戻ります。exec 呼び出しは Notifcation.php ファイルをロードし、それが CLI から実行されていることを認識するため、それ自体をインスタンス化し、適切なコマンド ライン オプションを取得し、通知を送信して終了します。
適切な通知メッセージと同じディレクトリに新しい notification.log があることを確認することで、これを確認できます。