찾다
백엔드 개발PHP 튜토리얼PHP API打包的一个实例,来自EtherPad

PHP API封装的一个实例,来自EtherPad

<?phpclass EtherpadLiteClient {  const API_VERSION             = 1;  const CODE_OK                 = 0;  const CODE_INVALID_PARAMETERS = 1;  const CODE_INTERNAL_ERROR     = 2;  const CODE_INVALID_FUNCTION   = 3;  const CODE_INVALID_API_KEY    = 4;  protected $apiKey = "";  protected $baseUrl = "http://localhost:9001/api";    public function __construct($apiKey, $baseUrl = null){    $this->apiKey  = $apiKey;    if (isset($baseUrl)){      $this->baseUrl = $baseUrl;    }    if (!filter_var($this->baseUrl, FILTER_VALIDATE_URL)){      throw new InvalidArgumentException("[{$this->baseUrl}] is not a valid URL");    }  }  protected function call($function, array $arguments = array()){    $query = array_merge(      array('apikey' => $this->apiKey),      $arguments    );    $url = $this->baseUrl."/".self::API_VERSION."/".$function."?".http_build_query($query);    // not all PHP installs have access to curl    if (function_exists('curl_init')){      $c = curl_init($url);      curl_setopt($c, CURLOPT_RETURNTRANSFER, true);      curl_setopt($c, CURLOPT_TIMEOUT, 20);      $result = curl_exec($c);      curl_close($c);    } else {      $result = file_get_contents($url);    }        if($result == ""){      throw new UnexpectedValueException("Empty or No Response from the server");    }        $result = json_decode($result);    if ($result === null){      throw new UnexpectedValueException("JSON response could not be decoded");    }    return $this->handleResult($result);  }  protected function handleResult($result){    if (!isset($result->code)){      throw new RuntimeException("API response has no code");    }    if (!isset($result->message)){      throw new RuntimeException("API response has no message");    }    if (!isset($result->data)){      $result->data = null;    }    switch ($result->code){      case self::CODE_OK:        return $result->data;      case self::CODE_INVALID_PARAMETERS:      case self::CODE_INVALID_API_KEY:        throw new InvalidArgumentException($result->message);      case self::CODE_INTERNAL_ERROR:        throw new RuntimeException($result->message);      case self::CODE_INVALID_FUNCTION:        throw new BadFunctionCallException($result->message);      default:        throw new RuntimeException("An unexpected error occurred whilst handling the response");    }  }  // GROUPS  // Pads can belong to a group. There will always be public pads that doesnt belong to a group (or we give this group the id 0)    // creates a new group   public function createGroup(){    return $this->call("createGroup");  }  // this functions helps you to map your application group ids to etherpad lite group ids   public function createGroupIfNotExistsFor($groupMapper){    return $this->call("createGroupIfNotExistsFor", array(      "groupMapper" => $groupMapper    ));  }  // deletes a group   public function deleteGroup($groupID){    return $this->call("deleteGroup", array(      "groupID" => $groupID    ));  }  // returns all pads of this group  public function listPads($groupID){    return $this->call("listPads", array(      "groupID" => $groupID    ));  }  // creates a new pad in this group   public function createGroupPad($groupID, $padName, $text){    return $this->call("createGroupPad", array(      "groupID" => $groupID,      "padName" => $padName,      "text"    => $text    ));  }  // AUTHORS  // Theses authors are bind to the attributes the users choose (color and name).   // creates a new author   public function createAuthor($name){    return $this->call("createAuthor", array(      "name" => $name    ));  }  // this functions helps you to map your application author ids to etherpad lite author ids   public function createAuthorIfNotExistsFor($authorMapper, $name){    return $this->call("createAuthorIfNotExistsFor", array(      "authorMapper" => $authorMapper,      "name"         => $name    ));  }  // SESSIONS  // Sessions can be created between a group and a author. This allows  // an author to access more than one group. The sessionID will be set as  // a cookie to the client and is valid until a certian date.  // creates a new session   public function createSession($groupID, $authorID, $validUntil){    return $this->call("createSession", array(      "groupID"    => $groupID,      "authorID"   => $authorID,      "validUntil" => $validUntil    ));  }  // deletes a session   public function deleteSession($sessionID){    return $this->call("deleteSession", array(      "sessionID" => $sessionID    ));  }  // returns informations about a session   public function getSessionInfo($sessionID){    return $this->call("getSessionInfo", array(      "sessionID" => $sessionID    ));  }  // returns all sessions of a group   public function listSessionsOfGroup($groupID){    return $this->call("listSessionsOfGroup", array(      "groupID" => $groupID    ));  }  // returns all sessions of an author   public function listSessionsOfAuthor($authorID){    return $this->call("listSessionsOfAuthor", array(      "authorID" => $authorID    ));  }  // PAD CONTENT  // Pad content can be updated and retrieved through the API  // returns the text of a pad   // should take optional $rev  public function getText($padID){    return $this->call("getText", array(      "padID" => $padID    ));  }  // sets the text of a pad   public function setText($padID, $text){    return $this->call("setText", array(      "padID" => $padID,       "text"  => $text    ));  }  // PAD  // Group pads are normal pads, but with the name schema  // GROUPID$PADNAME. A security manager controls access of them and its  // forbidden for normal pads to include a $ in the name.  // creates a new pad  public function createPad($padID, $text){    return $this->call("createPad", array(      "padID" => $padID,       "text"  => $text    ));  }  // returns the number of revisions of this pad   public function getRevisionsCount($padID){    return $this->call("getRevisionsCount", array(      "padID" => $padID    ));  }  // deletes a pad   public function deletePad($padID){    return $this->call("deletePad", array(      "padID" => $padID    ));  }  // returns the read only link of a pad   public function getReadOnlyID($padID){    return $this->call("getReadOnlyID", array(      "padID" => $padID    ));  }  // sets a boolean for the public status of a pad   public function setPublicStatus($padID, $publicStatus){    return $this->call("setPublicStatus", array(      "padID"        => $padID,      "publicStatus" => $publicStatus    ));  }  // return true of false   public function getPublicStatus($padID){    return $this->call("getPublicStatus", array(      "padID" => $padID    ));  }  // returns ok or a error message   public function setPassword($padID, $password){    return $this->call("setPassword", array(      "padID"    => $padID,      "password" => $password    ));  }  // returns true or false   public function isPasswordProtected($padID){    return $this->call("isPasswordProtected", array(      "padID" => $padID    ));  }}

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP와 Python : 다른 패러다임이 설명되었습니다PHP와 Python : 다른 패러다임이 설명되었습니다Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python : 그들의 역사에 깊은 다이빙PHP와 Python : 그들의 역사에 깊은 다이빙Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP와 Python 중에서 선택 : 가이드PHP와 Python 중에서 선택 : 가이드Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP 및 프레임 워크 : 언어 현대화PHP 및 프레임 워크 : 언어 현대화Apr 18, 2025 am 12:14 AM

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

PHP의 영향 : 웹 개발 및 그 이상PHP의 영향 : 웹 개발 및 그 이상Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?Apr 17, 2025 am 12:25 AM

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?Apr 17, 2025 am 12:24 AM

PHP에서는 클론 키워드를 사용하여 객체 사본을 만들고 \ _ \ _ Clone Magic 메소드를 통해 클로닝 동작을 사용자 정의하십시오. 1. 복제 키워드를 사용하여 얕은 사본을 만들어 객체의 속성을 복제하지만 객체의 속성은 아닙니다. 2. \ _ \ _ 클론 방법은 얕은 복사 문제를 피하기 위해 중첩 된 물체를 깊이 복사 할 수 있습니다. 3. 복제의 순환 참조 및 성능 문제를 피하고 클로닝 작업을 최적화하여 효율성을 향상시키기 위해주의를 기울이십시오.

PHP vs. Python : 사용 사례 및 응용 프로그램PHP vs. Python : 사용 사례 및 응용 프로그램Apr 17, 2025 am 12:23 AM

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)