面向对象进阶之:closure

/**
 * Class App
 *
 * 使用Closure bindTo实现路由添加.
 */
class App {
  protected $routers = [];
  protected $responseStatus = 200;
  protected $responseType = 'text/html';
  protected $responseBody = 'hello world';

  public function addRoute($routePath, Closure $routeCallback) {
    $this->routers[$routePath] = $routeCallback->bindTo($this, __CLASS__);
    return $this;
  }

  public function dispatch($currentPath = '') {
    if ($currentPath && isset($this->routers[$currentPath])) {
      $this->routers[$currentPath]();
    }

    header('HTTP/1.1 ' . $this->responseStatus);
    header('Content-type: ' . $this->responseType);
    header('Content-length: ' . mb_strlen($this->responseBody));
    print $this->responseBody;
  }

  public static function factory() {
    return new static();
  }
}

App::factory()->addRoute('home', function() {
  $this->responseBody = 'this is front page';
})->addRoute('news', function() {
  $this->responseBody = 'this is news page';
})->dispatch('news');


面向对象进阶之:Interface

/**
 *  使用Interface 实现收集不同源的文本数据.
 */

/**
 * Interface Documentable
 */
Interface Documentable {
  public function getID();
  public function getContent();
}

class DocumentStore {
  protected $data = [];

  public function addDocument(Documentable $document) {
    $key = $document->getId();
    $value = $document->getContent();
    $this->data[$key] = $value;
  }

  public function getDocument() {
    return $this->data;
  }
}

class HtmlDocument implements Documentable{

  protected $url;

  public function __construct($url) {
    $this->url = $url;
  }

  public function getID() {
    return $this->url;
  }

  public function getContent() {
    return file_get_contents($this->url);
  }
}

class StreamDocument implements Documentable {

  protected $resource;
  protected $buffer;

  public function __construct($resource, $buffer = 4096) {
    $this->resource = $resource;
    $this->buffer = $buffer;
  }

  public function getID() {
    return 'resouce-' . (int)$this->resource;
  }

  public function getContent() {
    $streamContent = '';
    rewind($this->resource);
    while (feof($this->resource) === false) {
      $streamContent .= fread($this->resource, $this->buffer);
    }
    return $streamContent;
  }
}

class CommandOuputDocument implements Documentable {

  protected $command;

  public function __construct($command) {
    $this->command = $command;
  }

  public function getID() {
    return $this->command;
  }

  public function getContent() {
    return shell_exec($this->command);
  }
}


$documentStore = new DocumentStore();
$htmldoc = new HtmlDocument('https://www.php.net');
$documentStore->addDocument($htmldoc);

$streamdoc = new StreamDocument();
$documentStore->addDocument($streamdoc);

$commanddoc = new CommandOuputDocument('cat /etc/hosts');
$documentStore->addDocument($commanddoc);

var_dump($documentStore->getDocument());