2013-06-04 4 views
2

파일 인 Notification.php은 클래스입니다. 그것의 구조는 다음과 같다 :현재 파일에서 exec 명령을 사용하여 다른 파일의 함수를 호출하는 방법

Class Notificaiton 
{ 
    public function sendNotification($token,$count) 
    { 
     // Here is the code for sending push notification(APNS) 
    }  
} 

일반적으로, 나는 아래의 방법 클래스의 객체를 만들기 위해 다른 PHP 파일에서이 기능을 그때 한 전화하고 전화를 걸 경우 :

$notification = new Notification(); 
$notification->sendNotification($token,$value); 

하지만 내가하고 싶은 것은 백그라운드 프로세스에서 이것을 호출하는 것입니다. 그래서 다음과 같이 exec() 명령을 사용 :

여기
exec("/usr/bin/php /path/to/Notification.php >> /path/to/log_file.log 2>&1 &"); 

내가 어떻게 function(sendNotificaiton())file(Notification.php)의 전화를 통과 매개 변수로 인수 할 수 있을까 : $을 토큰 $ 계산?

나는 exec/shell_exec/passthru commands을 찾았습니다. 그러나이 경우에 나는이 세 가지 명령에서 어떤 명령을 사용 했습니까?

나를 안내하십시오. 어떤 도움을 주시면 감사하겠습니다.

+0

비동기 실행을 찾는 경우 exec 만 사용할 수있는 것은 아닙니다. 멀티 스레딩을 고려할 수 있습니다. 장점과 단점에 대해서는 다음을 참조하십시오 : http://stackoverflow.com/questions/209774/does-php-have-threading/14201579#14201579 –

답변

6

더 나은 PHP 파일을 만들고 그 안에 메서드를 호출하는 것이 좋습니다. 추천

notificationCall.php :

<?php 
include 'notification.php'; 

$token = $argv[1]; 
$count = $arg2[2]; 
$notification = new Notification(); 
$notification->sendNotification($token,$count); 
?> 

간부 /path/to/log_file.log ("/ USR/빈/PHP /path/to/notificationCall.php 토큰 카운트 >> 2> 1 & & ");

+0

감사합니다. 그것은 완벽하게 작동합니다. 나는'exec/shell_exec/passthru commands'가 도와주세요. 그러나이 경우에 나는이 세 가지 명령에서 어떤 명령을 사용 했습니까? – Ponting

+0

패스 스루는 다른 것보다 더 많은 우위를 가지고 있습니다. 여기를 참조하십시오. http://chipmunkninja.com – rams0610

+0

내가 언급 한 사이트에서 패스 스루와 관련된 내용을 볼 수 없습니다. – Ponting

1

예제는 매우 간단하며 바주카포로 파리를 죽이는 것이지만 http://www.gearman.org/ 또는 http://www.rabbitmq.com/과 같은 방법은 어떨까요? 이러한 서비스는 백그라운드에서 물건을 실행하는 데 적합합니다.

내가 사용하고 리눅스 웹 서버와의 cPanel에서
1

를 넣고 코드

A)

/usr/bin/php -q /home/username/public_html/path/to/Notification.php 

및 B) 일부 서버에서 나를 위해

lynx --dump http://yourlink.com/path/to/Notification.php > /path/to/log_file.log 

은의 방법 A를 작동 일부 서버는 메소드 B를 작동합니다. 둘 다 시도 할 수 있습니다. 나는 그것이 당신을 돕기를 바랍니다.

2

과 같이, 알림 클래스 구조 방법을 추가

function __construct() { 
    if(isset($_GET['action']) && $_GET['action']=='sendnotification') { 
     $this->sendNotification(); 
    } 
} 

다음과 같이 당신의 간부 명령을 실행

exec("/usr/bin/php /path/to/Notification.php?action=sendnotification >> 
/path/to/log_file.log 2>&1"); 

토큰 $ 횟수도 간부 내에서 GET 매개 변수로 제공 할 수 $ 명령.

2

커맨드 라인 실행을 호출하기 위해 별도의 스크립트를 사용하지 않는 것이 좋습니다.

testNotification.PHP는

<?php 
include_once 'Notification.php'; 
use Bubba\Util\Notification; 

$Notification = new Notification(); 
$Notification->sendNotification('some1token', 33); 

이것은 우리의 알림 클래스 파일이이 웹에 액세스 할 수없는 라이브러리 디렉토리에있을 것입니다 예상하고 있지만, 같은 디렉토리에 있다고 가정합니다.

이 경우

<?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; 
    } 
} 

Notification.php, 당신은 단지 http://your.localhost.net/testNotification.php를 검색 할 수 있으며 testNotification는 통지 객체를 생성하고, 통지 함수를 호출합니다. notify 함수는 CLI 호출이 아니므로 exec 호출을 수행하고 즉시 리턴합니다. exec 호출은 Notifcation.php 파일을로드하고 CLI에서 실행 중임을 인식하여 인스턴스를 생성하고 적절한 명령 행 옵션을 잡고 알림을 보내고 종료합니다.

새 알림 .log가 적절한 알림 메시지가있는 동일한 디렉토리에 있음을 확인할 수 있습니다.

관련 문제