4d47 / http-resource
HTTP 资源
v3.0.0
2014-09-05 17:22 UTC
Requires
- php: >= 5.3.0
- 4d47/http-exceptions: 1.*
Requires (Dev)
- phpunit/phpunit: 3.7.*
README
PHP 悖论:PHP 是一个网络框架。任何使用 PHP 的尝试都将导致构建一个网络框架。
安装
composer require 4d47/http-resource:3.*
用法
namespace App; # First you define a 'class' of URLs. # That's a set of documents that share the same structure of data and operations. # Instances of the class will represents a specific URL. class Product extends \Http\Resource { # The `$path` static variable holds the URL pattern that this resource # match. When matched, the instance will have properties assigned with # the pattern variables. Parenthesis can be used for optional variables, # colon denote a variable and a star matches anything. eg: `/foo((/:bar)/*)` public static $path = '/products/:name'; # Then you implement HTTP methods, GET, POST, PUT, etc # to update the instance resource representation. # Server errors (5xx), client errors (4xx) and redirects (3xx) are sent by throwing # [http exceptions](http://github.com/4d47/php-http-exceptions). public function get() { if ($this->name == 'bazam') throw new \Http\NotFound(); $this->price = 12; } # Implement any other methods you like public function __toString() { return sprintf("%s, %d$$", ucfirst($this->name), $this->price); } }
默认 render
使用位于 views
目录并以类名命名的脚本。例如 views/app/product.php
。实例属性在包含之前将被 extract
。$this
指的是资源本身,它可以用来分配属性或调用助手方法。link
用于引用资源路径。
<a href="<?= \App\Product::link($name) ?>"> <?= $this ?> </a>
如果 views 子路径中存在名为 layout.php
的文件,则将使用第一个。变量 $content
将包含第一个视图的结果,同时 $this
也将可用。例如使用 views/layout.php
。
<html> <title><?= $this->title ?></title> <body><?= $content ?></body> </html>
最后,您可以通过处理资源列表,在您的 index.php
中引导所有内容。
\Http\Resource::handle(['App\Product']);
有关代码的基本布局,请参阅 4d47/php-start。