[英]Toggle settings with hashtags, PHP
我正在開發一個PHP應用程序,它通過Twilio接收傳入的SMS消息,並根據主題標簽和設置更改用戶首選項。 例如,如果用戶想要從站點禁用SMS警報,則會將#sms off
文本#sms off
。
下面是我為處理這個任務而放在一起的代碼,但我覺得它很臃腫,可以清理一下。 任何有關如何從另一個(希望更整潔)角度處理此任務的建議將不勝感激。
這很棘手,因為傳入的hashtag可以在任何cAsE中 - #SMS off
, #Sms Off
等。我通過使命令和設置大寫來解決這個問題。
這是我到目前為止 -
<?php
$body = trim($_POST['Body']);
$pos = strripos($body, '#'); //Find position of hashtag in body
if ($pos != 0) {
//Hashtag was not first, therefor this is a normal incoming SMS
//without commands
echo "Normal SMS message";
} else if ($pos == 0) {
//This is a command SMS, we need to react to it
preg_match_all('/#(\w+)/',$body,$matches); // Isolate the hashtag
// Change hashtag, complete with #, to uppercase
//This is to prevent case issues in the incoming SMS
$command = strtoupper($matches[0][0]);
//Remove the hashtag from the SMS, convert the remaining string to upper,
//and trim it to isolate
$setting = str_ireplace($command, '', $body);
$setting = strtoupper(trim($setting));
//Switch for available commands
switch ($command) {
case '#DISPATCH':
if ($setting == 'ON') {
echo 'Dispatch alert has been turned on';
} else if ($setting == 'OFF') {
echo 'Dispatch alert has been turned off';
} else {
'Missing setting. Please reply with #dispatch on or #dispatch off to set.';
}
break;
case '#SMS':
if ($setting == 'ON') {
echo 'SMS alerts have been turned on';
} else if ($setting == 'OFF') {
echo 'SMS alerts have been turned off';
} else {
'Missing setting. Please reply with #sms on or #sms off to set.';
}
break;
default:
echo 'I do not recognize this command. Please enter either #dispatch or #sms followed by on or off to set.';
break;
}
}
謝謝!
您可能會發現explode()
更容易使用。 像這樣(未經測試):
$pos = strripos($body, '#'); //Find position of hashtag in body
if ($pos != 0) {
echo "Normal SMS message";
} else {
// The input needs to be all uppercase, and split apart by the space
$pieces = explode(" ",strtoupper($body));
// Our command will be the first item
$command = array_shift($pieces);
// The rest will be the setting
$setting = trim(implode(" ",$pieces));
switch($command) {
...
我會做一個更面向對象的方法。
例如,代碼可能如下所示:
$sms = new SMS($_POST['Body']);
SMS將負責解析所有內容並抽象出任何相關內容。
if ($sms->hasCommand()) {
$commandDispatcher = new SMSCommandDispatcher($sms->getCommand(), $sms->getCommandArguments());
$commandDispatcher->dispatch();
}
SMSCommandDispatcher將知道存在哪些命令並執行它們:
它看起來像這樣:
class SMSCommandDispatcher {
protected $knownCommands = array(
'dispatch' => 'DispatchCommand',
'sms' => 'SMSCommand',
);
public function __construct($cmd, $args) {
if (!isset($this->knownCommands[$cmd])) throw new InvalidArgumentException('Unknown command');
$this->commandInstance = new $this->knownCommands[$cmd]($args);
}
public function dispatch() {
$this->commandInstance->invoke();
}
}
然后你有SMSCommand和DispatchCommand類當然......
抽象是非常有幫助擺脫臃腫。 希望這對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.